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?
We can extract the first list elements and convrert to numeric
Or with
base R
usingregmatches/regexpr
Or with
scan
after removing the curly bracketsYou can also use
scan
:Not sure if performance is a concern but I was curious so here's a benchmark:
on longer string:
on original short string:
You can try using
gsub
to first replace{
and}
and then split in vector usingstrsplit
. Finally, convert it to numeric as:You can do this in base R as
or