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
さて、この段階で、インポート/変換のプロセスを自動化しました(1行分)。
最初の質問: すべての行が処理されるときに、データをどのように表示したいですか? 2 番目の質問: 結果として、正確には何を入れたいですか? 残差、適合値? 何から必要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
したがって、各グループ (または元のスプレッドシートの行) には、(予想どおり) 切片と勾配の 2 つの係数があるため、係数をどのように内部に収めたいかわかりません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 が必要な場合はお知らせください。