我的数据以此格式存储
District Andamans (01), Andaman & Nicobar Islands (35)
在单个列的所有行中。我想使用R将它们添加到01-35格式的新列中。我尝试使用
as.numeric(unlist(str_extract_all(abc$District, '\\d+')))
但是它给了我分离的ioutputs,我无法加载到与上面数据列(590列)相同长度(1180列)的单个列中。
答案 0 :(得分:3)
如果我们需要采用特定格式,请使用lapply
循环浏览list
(str_extract_all
返回list
和paste
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")