Turning a string of numbers into a list of numbers in R

  • A+
Category:Languages

Apologies if this question is too easy, I know how to do it in Python but I currently need it in R.

As part of an SQL query I get a variable with some numbers (the length can vary), as a string, like so:

x <- "{0.5,0.25,0.75,0.5}"  

I can get rid of the brackets and commas, thus:

library(stringr) library(dplyr) y <- x %>%   str_remove_all("[{]") %>%   str_remove_all("[}]") %>%   strsplit(",") 

...but the output which I receive is still a list of strings:

> y [[1]] [1] "0.5"  "0.25" "0.75" "0.5" 

How do I make sure y is always a list of numbers?

 


You can do this in base R as

as.numeric(strsplit(substr(x, 2, nchar(x) - 1), ',')[[1]]) 

or

as.numeric(strsplit(gsub('[{]|[}]', '', x), ',')[[1]]) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: