我有一个表格(d.tab
),其中包含问卷答案对。其中一些是单选答案,一些是多选题。我想从它的数值中查找单选答案的文本值。为此,我有一个查询表(d.lookup
)。基于其他数据框映射替换某些行中的值
我尝试过merge
这些,但它有点难看,因为我现在必须过滤掉value != answer_id
的所有行。有没有更漂亮的方式做到这一点,可能使用plyr
或dplyr
或tidyr
?
tab = '
question_id question_type subject value
1 single-choice 1 1
2 multiple-choice 1 2
3 single-choice 1 2
1 single-choice 2 2
2 multiple-choice 2 3,4
3 single-choice 2 2
'
lookup = '
question_id answer_id answer_text
1 1 female
1 2 male
3 1 no
3 2 yes
'
d.tab = read.table(text = tab, header = TRUE)
d.lookup = read.table(text = lookup, header = TRUE)
merge(d.tab, d.lookup, by = "question_id", all.x = TRUE)
我不想multiple-choice
行做任何事情,但如果answer_id
的比赛中value
简单地更新原来的数据帧从d.tab
的answer_text
的实际文本,以取代value
。
我知道我可以做:
merge(d.tab, d.lookup, by.x = c("question_id", "value"), by.y = c("question_id", "answer_id"), all.x = TRUE)
但是,这给了我一个新列answer_text
与原value
还在那里,我不需要。
您可以通过合并多个列,即使可能有不同的名称。你真的只想合并单选答案是正确的吗?否则,具有'3,4'的行会有点棘手。 – Stibu
是的,我不想对多选行做任何事情。这些仅仅是为了表明我只需要替换一部分值。 – slhck
查看更新的问题;我只注意到我可以做这个多键合并,但它并没有完全达到我所需要的。 – slhck