如何在R中将数据帧从宽格式转换为长格式?

时间:2013-06-12 08:54:01

标签: r reshape

我是R.的新手。我正在尝试以上述格式从Excel中读取数据

x1  x2  x3  y1  y2  y3  Result
1   2   3   7   8   9    
4   5   6   10  11  12   

和R中的data.frame应该以第一行提到的格式获取数据

x   y
1   7
2   8
3   9

然后我想使用lm()并将结果导出到结果列。

我想为n行自动执行此操作,即一旦第一列的结果导出到Excel,我就要导入第二行的数据。

请帮助。

1 个答案:

答案 0 :(得分:3)

library(gdata)
# this spreadsheet is exactly as in your question

df.original <- read.xls("test.xlsx", sheet="Sheet1", perl="C:/strawberry/perl/bin/perl.exe")
#
#
> df.original
  x1 x2 x3 y1 y2 y3
1  1  2  3  7  8  9
2  4  5  6 10 11 12
#
# for the above code you'll just need to change the argument 'perl' with the
# path of your installer
#
# now the example for the first row
#
library(reshape2)

df <- melt(df.original[1,])

df$variable <- substr(df$variable, 1, 1)

df <- as.data.frame(lapply(split(df, df$variable), `[[`, 2))

> df
  x y
1 1 7
2 2 8
3 3 9

现在,在这个阶段,我们自动化了输入/转换过程(一行)。

第一个问题:在处理每一行时,您希望数据看起来如何? 第二个问题:结果,你想要什么?残值,拟合值?您需要lm()

编辑:

好的,@ kapil告诉我df的最终形状是否符合您的想法:

library(reshape2)
library(plyr)

df <- adply(df.original, 1, melt, .expand=F)
names(df)[1] <- "rowID"

df$variable <- substr(df$variable, 1, 1)

rows <- df$rowID[ df$variable=="x"] # with y would be the same (they are expected to have the same legnth)
df <- as.data.frame(lapply(split(df, df$variable), `[[`, c("value")))
df$rowID <- rows

df <- df[c("rowID", "x", "y")]

> df
  rowID x  y
1     1 1  7
2     1 2  8
3     1 3  9
4     2 4 10
5     2 5 11
6     2 6 12

关于您可以用这种方式计算每个rowID(它指的是xls文件中的实际行)的系数:

model <- dlply(df, .(rowID), function(z) {print(z); lm(y ~ x, df);})

> sapply(model, `[`, "coefficients")
$`1.coefficients`
(Intercept)           x 
          6           1 

$`2.coefficients`
(Intercept)           x 
          6           1 

因此,对于每个组(或原始电子表格中的行),您(按预期)有两个系数,截距和斜率,因此我无法弄清楚您希望系数如何适合data.frame(特别是在“长”的方式,它出现在上面)。但如果您希望data.frame保持“广泛”模式,那么您可以试试这个:

# obtained the object model, you can put the coeff in the df.original data.frame
#
> ldply(model, `[[`, "coefficients")
  rowID (Intercept) x
1     1           6 1
2     2           6 1

df.modified <- cbind(df.original, ldply(model, `[[`, "coefficients"))

> df.modified
  x1 x2 x3 y1 y2 y3 rowID (Intercept) x
1  1  2  3  7  8  9     1           6 1
2  4  5  6 10 11 12     2           6 1

# of course, if you don't like it, you can remove rowID with df.modified$rowID <- NULL

希望这会有所帮助,如果您想要df的“长”版本,请告诉我。

相关问题