Reputation: 369
one column of my dataset looks like below;
"[3, 4, 5, 6]"
and I want to split every single value of this vector-like below as numeric;
3, 4, 5, 6
What can I do?
Thank you for your answers.
Upvotes: 2
Views: 881
Reputation: 46856
For this vector
x = "[3, 4, 5, 6]"
find all matches of a sequence of 1 or more digits and extract the matches from the original location
match = gregexpr("[[:digit:]]+", x)
values = regmatches(x, match)
This is a list of character values; coerce to integer, e.g., allowing x
to be more than length 1
lapply(values, as.integer)
Upvotes: 2
Reputation: 5254
Remove the brackets and split the string using the commas. strsplit()
returns a list. You want a vector, so let us unlist()
it and convert it to numerics.
x <- "[3, 4, 5, 6]"
x <- gsub("\\[|\\]","", x)
y <- as.numeric(unlist(strsplit(x, ",", fixed=TRUE)))
y
#> [1] 3 4 5 6
Created on 2021-05-01 by the reprex package (v2.0.0)
Upvotes: 3