【发布时间】:2013-12-11 19:42:24
【问题描述】:
我有两个 data.frames,(df1, df2),我想将 P1-P10 列中的值替换为 df1$V2 的值,但保留 df2 的前两列。
df1 = data.frame(V1=LETTERS, V2=rnorm(26))
df2 <- data.frame(Name=sample(LETTERS, 6), bd=sample(1:6), P1=sample(LETTERS,6), P2=sample(LETTERS, 6), P3=sample(LETTERS, 6), P4=sample(LETTERS, 6), P5=sample(LETTERS, 6), P6=sample(LETTERS, 6), P7=sample(LETTERS, 6), P8=sample(LETTERS, 6), P9=sample(LETTERS, 6), P10=sample(LETTERS, 6))
我的方法如下:
df3 <- matrix(setNames(df1[,2], df1[,1])[as.character(unlist(df2[,3:12]))], nrow=6, ncol=10)
df4 <- data.frame(cbind(df2[,1:2], df3))
这给了我想要的输出,我的真实数据有 10,000 列,有什么办法可以避免 cbind 步骤或加快处理速度?
> df4
Name bd X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 V 6 -1.8991102 0.40269050 -0.1517500 -2.5297829 1.5315622 1.4897071 1.364071 -1.2443708 -1.3197276 -0.4917057
2 T 1 -2.5297829 -0.44614123 -0.1894970 -0.6693774 -0.1517500 -1.0650962 -0.151750 -0.4461412 -0.6693774 -1.1351770
3 R 5 -0.6693774 0.09059365 -2.5297829 0.3233827 -0.9383348 -0.4461412 1.281797 1.5315622 1.4897071 -0.4461412
4 B 4 -0.4461412 -0.93833476 -1.2443708 -0.4461412 -0.1894970 -0.9383348 -1.135177 -1.8991102 -0.1894970 0.4026905
5 K 2 -1.0180271 -1.06509624 -0.1939600 -0.1894970 1.4897071 -0.6693774 -1.899110 -1.3197276 1.5315622 -0.1517500
6 Y 3 1.5315622 -0.19396005 -0.4917057 -0.4664239 -1.8991102 0.4026905 -1.065096 -0.9383348 -1.2443708 -0.4664239
谢谢
【问题讨论】:
-
在您的示例中,P1-P10 是因子。在你的数据集中真的是这样吗?
-
是的,它们是我数据集中的因素,抱歉我回复晚了
-
好的,我的答案现在适用于因子和字符。
标签: r