【发布时间】:2012-11-26 12:39:30
【问题描述】:
我有什么:
我有一个包含以下列的“主”数据框:
userid, condition
由于有四个实验条件,我也有四个携带答案信息的数据框,以下列:
userid, condition, answer1, answer2
现在,我想加入这些,因此所有用户 ID、条件及其对这些条件的答案的组合都会合并。每个条件只应在每行的相应列中有正确答案。
简短、独立的示例:
master = data.frame(userid=c("foo","foo","foo","foo","bar","bar","bar","bar"), condition=c("A","B","C","D","A","B","C","D"))
cond_a = data.frame(userid=c("foo","bar"), condition="A", answer1=c("1","1"), answer2=c("2","2"))
cond_b = data.frame(userid=c("foo","bar"), condition="B", answer1=c("3","3"), answer2=c("4","4"))
cond_c = data.frame(userid=c("foo","bar"), condition="C", answer1=c("5","5"), answer2=c("6","6"))
cond_d = data.frame(userid=c("foo","bar"), condition="D", answer1=c("7","7"), answer2=c("8","8"))
如何将所有条件合并到主表中,使主表如下所示?
userid condition answer1 answer2
1 bar A 1 2
2 bar B 3 4
3 bar C 5 6
4 bar D 7 8
5 foo A 1 2
6 foo B 3 4
7 foo C 5 6
8 foo D 7 8
我尝试了以下方法:
temp = merge(master, cond_a, all.x=TRUE)
这给了我:
userid condition answer1 answer2
1 bar A 1 2
2 bar B <NA> <NA>
3 bar C <NA> <NA>
4 bar D <NA> <NA>
5 foo A 1 2
6 foo B <NA> <NA>
7 foo C <NA> <NA>
8 foo D <NA> <NA>
但是一旦我这样做了……
merge(temp, cond_b, all.x=TRUE)
条件B 没有值。怎么会?
userid condition answer1 answer2
1 bar A 1 2
2 bar B <NA> <NA>
3 bar C <NA> <NA>
4 bar D <NA> <NA>
5 foo A 1 2
6 foo B <NA> <NA>
7 foo C <NA> <NA>
8 foo D <NA> <NA>
【问题讨论】:
-
我刚刚注意到我可以做
merge(temp, cond_b, all=TRUE),但这会给我额外的行,其中包含NAs。不理想。 -
这会有帮助吗?
temp <-rbind(cond_a,cond_b,cond_c,cond_d) temp[order(temp["userid"]),]或者与master中的内容有什么特定的关系? -
在这篇文章的简单案例中,确实如此!我在主数据集中有一些额外的列,这就是为什么它在我的特定数据集中不起作用的原因——但我没有提到这一点,所以也可以随意发布它作为示例。