user299791
user299791

Reputation: 2070

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

Upvotes: 1

Views: 2496

Answers (2)

ctbrown
ctbrown

Reputation: 2361

Use strsplit:

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

See the documentation on ?strsplit for details.

Upvotes: 1

konvas
konvas

Reputation: 14366

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.

Upvotes: 3

Related Questions