1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use strsplit:

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

See the documentation on ?strsplit for details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.