从string的vector中提取数字
我有这样的string:
years<-c("20 years old", "1 years old") 我想grep只有从这个向量的数字号码。 预期的输出是一个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)) 
 我认为替代是解决问题的间接方式。 如果你想检索所有的数字,我build议gregexpr : 
 matches <- regmatches(years, gregexpr("[[:digit:]]+", years)) as.numeric(unlist(matches)) 
 如果你有一个string中的多个匹配,这将得到所有的人。 如果您只对第一场比赛感兴趣,请使用regexpr而不是gregexpr ,您可以跳过未unlist 。 
下面是Arun第一个解决scheme的替代scheme,它有一个简单的Perl类正则expression式:
 as.numeric(gsub("[^\\d]+", "", years, perl=TRUE)) 
你也可以摆脱所有的字母:
 as.numeric(gsub("[[:alpha:]]", "", years)) 
可能这是不太普遍的。
  更新由于extract_numeric已被弃用,我们可以使用readr包中的readr 。 
 library(readr) parse_number(years) 
 这是extract_numeric另一个选项 
 library(tidyr) extract_numeric(years) #[1] 20 1 
或者干脆:
 as.numeric(gsub("\\D", "", years)) # [1] 20 1 
 一个stringrpipe道解决scheme: 
 library(stringr) years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric 
在Gabor Grothendieck 发布的邮件列在r-help邮件列表后
 years<-c("20 years old", "1 years old") library(gsubfn) pat <- "[-+.e0-9]*\\d" sapply(years, function(x) strapply(x, pat, as.numeric)[[1]]) 
从开始位置的任何string中提取数字。
 x <- gregexpr("^[0-9]+", years) # Numbers with any number of digits x2 <- as.numeric(unlist(regmatches(years, x))) 
从任何stringINDEPENDENT中提取数字。
 x <- gregexpr("[0-9]+", years) # Numbers with any number of digits x2 <- as.numeric(unlist(regmatches(years, x)))