简体   繁体   中英

how to convert a string into numeric values in R

I have a string like "[0 0.1 0.2 0.4]" and what I want is to strip parentheses and retrieve values as numeric. I am able to strip parentheses, but when it comes to convert to numeric, then I have an error with NA:

cleanList <- function(aString){
   temp <- gsub("\\[|\\]", "", aString)
   as.numeric(temp)
}

is there a way to convert each of the character in the string into numbers?

EDIT: here's another approach that uses stringr:

cleanList <- function(aString){
   as.numeric(str_extract_all(aString,"\\(?[0-9,.]+\\)?")[[1]])
}
cleanList("[0 0.1 0.2 0.4]")
[1] 0.0 0.1 0.2 0.4

You need to split temp into a vector and then call as.numeric on that. Assuming the numbers in temp are separated by spaces,

temp2 <- unlist(strsplit(temp, " "))
as.numeric(temp2)
# 0.0 0.1 0.2 0.4

Alternatively, do.call(as.numeric, strsplit(temp, " ")) will work too.

Use strsplit :

as.numeric( strsplit( temp, " " )[[1]] ) 

See the documentation on ?strsplit for details.

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