2

In previous message Convert table into matrix by column names

I want to use the same approach for an csv table or an table in R. Could you mind to teach me how to modify the first command line?

x <- read.table(textConnection(' models cores  time 4 1 0.000365 4 2 0.000259 4 3 0.000239 4 4 0.000220 8 1 0.000259 8 2 0.000249 8 3 0.000251 8 4 0.000258' ), header=TRUE)   

library(reshape) cast(x, models ~ cores)

Should I use following for a data.csv file

x <- read.csv(textConnection("data.csv"), header=TRUE)

Should I use the following for a R table named as xyz

x <- xyz(textConnection(xyz), header=TRUE)

Is it a must to have the textConnection for using cast command?

Thank you.

Community
  • 1
  • 1
Catherine
  • 5,345
  • 11
  • 30
  • 28
  • 3
    You wouldn't happen to be the same person as the other Catherine of hereabouts who doesn't accept questions and posts simple Qs without having bothered to read the manuals we keep asking her too? – Gavin Simpson Apr 11 '11 at 16:26
  • 6
    Welcome back, Catherine. Oh, how we've missed you. – Andrie Apr 11 '11 at 16:28
  • 1
    Ar you sure `xyz` is a table? Far more likely it is a data frame. What does `class(xyz)` say? Why would you think `xyz` could be used as a function? If `xyz` is already *in* R, why are you trying to read it in? Is it something you saved earlier perhaps? If the latter, see `?load`. – Gavin Simpson Apr 11 '11 at 17:09

1 Answers1

19

Several years later...

read.table and its derivatives like read.csv now have a text argument, so you don't need to mess around with textConnections directly anymore.

read.table(text = "
x y z
1 1.9 'a'
2 0.6 'b'
", header = TRUE)

The main use for textConnection is when people who ask questions on SO just dump their data onscreen, rather than writing code to let answerers generate it themselves. For example,

Blah blah blah I'm stuck here is my data plz help omg
x y z
1 1.9 'a'
2 0.6 'b'
etc.

In this case you can copy the text from the screen and wrap it in a call to textConnection, like so:

the_data <- read.table(tc <- textConnection("x y z
1 1.9 'a'
2 0.6 'b'"), header = TRUE); close(tc)

It is much nicer when questioners provide code, like this:

the_data <- data.frame(x = 1:2, b = c(2.9, 0.6), c = letters[1:2])

When you are using you own data, you shouldn't ever need to use textConnection.
my_data <- read.csv("my data file.csv") should suffice.

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • 3
    I think you are missing a note to read `?read.csv` and a link to the R Data Import/Export manual [ http://cran.r-project.org/doc/manuals/R-data.html ] somewhere in there :-) – Gavin Simpson Apr 11 '11 at 17:06