简体   繁体   中英

Extract numbers from string values of one column in df to another

I would like to extract numbers from string values in one of the columns of my data frame and put them into another column. All the values in column "a" are unique. This code brings column "b" full of NA

df$b <- lapply(df$a,function(i){as.numeric(substr(df[i,"a"], 
regexpr("abc[0-9]+",df[i,"a"]) + 2, regexpr("abc[0-9]+",df[i,"a"]) + 
attr(regexpr("abc[0-9]+", df[i,"a"]), "match.length") -1))})

We can try

 library(stringr)
 as.numeric(unlist(str_extract_all(df$a, '\\d+')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM