R-从列中的字符串中提取数字

时间:2017-09-30 18:20:01

标签: r

我的数据以此格式存储

District Andamans (01), Andaman & Nicobar Islands (35)

在单个列的所有行中。我想使用R将它们添加到01-35格式的新列中。我尝试使用

 as.numeric(unlist(str_extract_all(abc$District, '\\d+')))

但是它给了我分离的ioutputs,我无法加载到与上面数据列(590列)相同长度(1180列)的单个列中。

1 个答案:

答案 0 :(得分:3)

如果我们需要采用特定格式,请使用lapply循环浏览liststr_extract_all返回listpaste

library(stringr)
sapply(str_extract_all(abc$District, "\\d+"), function(x) paste(x, collapse="-"))
#[1] "01-35"

数据

abc <- structure(list(District = "District Andamans (01), Andaman & Nicobar Islands (35)"), .Names = "District", row.names = c(NA, 
-1L), class = "data.frame")