comma separated string to list in r
41,618
This is a basic strsplit
problem:
x <- "a,b,c"
as.list(strsplit(x, ",")[[1]])
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "b"
#
# [[3]]
# [1] "c"
strsplit
creates a list
and the [[1]]
selects the first list item (we only have one, in this case). The result at this point is just a regular character vector, but you want it in a list
, so you can use as.list
to get the form you want.
With the same logic you can use el
:
as.list(el(strsplit(x, ",")))
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "b"
#
# [[3]]
# [1] "c"
Or scan
:
as.list(scan(text = x, what = "", sep = ","))
# Read 3 items
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "b"
#
# [[3]]
# [1] "c"
Related videos on Youtube
Author by
umbersar
Updated on December 17, 2020Comments
-
umbersar over 3 years
I have a comma separated string in R:-
"a,b,c"
I want to convert it into a list which looks like this:
list("a","b","c")
How do I do that?
-
vrajs5 almost 10 yearsWhat you have tried till now?
-
-
umbersar almost 10 yearsPerfect. I was trying strsplit(x,",") which was giving me a list of single element which was not what i needed. I have to wait 9 minutes before I can mark your answer as accepted.