开发者

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

开发者 https://www.devze.com 2023-02-24 00:56 出处:网络
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?

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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号