简体   繁体   中英

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.

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 textConnection s 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
xyz
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM