0

我是 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,然后我想为第二行导入数据。

请帮忙。

4

1 回答 1

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 的“长”版本,请告诉我。

于 2013-06-12T11:00:38.600 回答