Home > Mobile >  How to convert strings to a list in R
How to convert strings to a list in R

Time:10-24

I have a lot of strings (thousands) that I want to make them elements of a list, such as my_list = as.list() so I can call them by index such as my_list[2] etc. I have tried

my_string = "SNHG12, SYT1, PTPRO, CATIP-AS1, LINC00326, PLEKHO2, LPCAT2, PTGS1, OLFM1, RNF130, AL121987.2, TNNI2, AC099568.1, SP100, CR1, PRKCD, HHEX, LINC01320, SYNDIG1, LMAN1, RTN1, CATSPER1, MED13L, FRMD4A, LINC00470, AC231981.1, AC126175.2, AC012066.2"
my_list = as.list(strsplit(my_string, ","))
my_list
length(my_list)

It will result in a list with length 1 output meaning a list with one element. However, I want that the list will have length(the number of strings) so that it should be my_list = as.list("SNHG12", "SYT1", "PTPRO", ...). How I can do that?

CodePudding user response:

You could do:

string <- strsplit(my_string, split=",")[[1]]
lapply(seq_along(string), function(i) string[i])

CodePudding user response:

After you unlist it you can use as.list

as.list(unlist(strsplit(my_string, ","), use.names = F))

The problem you are encountering is that strsplit already returns a list. That returned list is the same length as your input. In your example length(my_string) is 1. So, you are getting a list of length 1. Since you already have a list as.list is not doing anything.

  • Related