ZsideZ ZsideZ - 1 year ago 92
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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download