Catherine
Catherine

Reputation: 5417

R: load R table or csv file with the textconnection command

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.

Upvotes: 2

Views: 7222

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121077

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.

Upvotes: 20

Related Questions