Search code examples
rsplitstrsplitcsv

Split list into dataframe at comma delimiter


This may be a duplicate, but after some time I still have not found a simple, adequate answer for R.

I have a list answers containing comma delimited data of varying types (numbers, characters, strings, dates) in numerous rows. How do I split it up so that each row has multiple columns with each data value in it?

I have been trying with the strsplit and separate functions but been unsuccessful.


My data current looks like this:

[[2,4,6,Yes,No,ABC,date,(not asked),2018-01-04][1,3,5,No,Yes,DEF,date,|I don't know|, 2018-04-03]]

And I want to turn it into a data frame like this:

    V1  V2  V3  V4   V5   V6   V7     V8            V9     
1   2   4   6   Yes  No   ABC  date   (not asked)   2018-01-04

2   1   3   5   No   Yes  DEF  date   I don't know  2018-04-03  

I have tried this:

new_answers<-read.csv(text=gsub("\\,","\n", answers), # replace "," with linefeeds
         header = FALSE)

but this separates the data values vertically (into a super long column), rather than horizontally (into a dataframe with multiple columns).


Solution

  • Replace all "]" with linefeeds and remove "["'s, tehn process with read.csv:

    txt <- "[[2,4,6,Yes,No,ABC,date,(not asked),2018-01-04][1,3,5,No,Yes,DEF,date,|I don't know|, 2018-04-03]]"
    
    read.csv(text=gsub("\\[", "",   #remove "["
                       gsub("\\]","\n", txt)), # replace "]" w/ R-lf's
               header = FALSE, col.names = LETTERS[1:9])
      A B C   D   E   F    G              H           I
    1 2 4 6 Yes  No ABC date    (not asked)  2018-01-04
    2 1 3 5  No Yes DEF date |I don't know|  2018-04-03