ZsideZ ZsideZ - 1 month ago 17
R Question

Create R dataframe from single string containing elements and whitespace

I have string that looks like this

string <- "\n\t\t\t1,2\n\t\t\t3,4\n\t\t"


And I need to create following data frame

1 2
3 4


One way is to use strsplit function, but it feels that there must be much better way of doing it.
Any help will be appreciated.

Answer

You can convert a character string to a thing that behaves a bit like a file with textConnection and then feed it to read.csv:

> read.csv(textConnection(string),head=FALSE)
  V1 V2
1  1  2
2  3  4
3 NA NA

the stray tabs after the last newline produce that last line of NA values, you'd need to take care of those some way.

Comments