从字符串向量中提取数字 [英] Extracting numbers from vectors of strings

查看:53
本文介绍了从字符串向量中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串:

years<-c("20 years old", "1 years old")

我只想从这个向量中提取数字.预期输出是一个向量:

I would like to grep only the numeric number from this vector. Expected output is a vector:

c(20, 1)

我该怎么做?

推荐答案

怎么样

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))

这篇关于从字符串向量中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆