2017-01-06 37 views
0

我有几个变量的数据帧:R:如何创建一个基于另一列的某些值的值的新列?

Subj DashedOrQuest ItemNo TimesOrCorrect 
1 dashed  243 859 
1 dashed  243 648 
1 dashed  243 655 
1 dashed  243 389 
1 question  243 1 
1 dashed  244 465 
1 dashed  244 844 
1 dashed  244 578 
1 dashed  244 713 
1 question  244 0 

我想什么做的是创建一个新列“探秘”,使每个货号会有这是在TimesOrCorrect为“数问题“在DashedOrQuest中的价值。换句话说,它应该是这样的

Subj DashedOrQuest ItemNo TimesOrCorrect Quest 
1 dashed  243 859   1 
1 dashed  243 648   1 
1 dashed  243 655   1 
1 dashed  243 389   1 
1 question  243 1    1 
1 dashed  244 465   0 
1 dashed  244 844   0 
1 dashed  244 578   0 
1 dashed  244 713   0 
1 question  244 0    0 

任何提示如何在R中做到这一点?提前致谢!

+0

我认为它仍然是一个有点不清楚你在问什么。你可以添加一个更长的例子,或者尝试更多地解释问题/列吗? –

回答

0

我们可以使用data.table

library(data.table) 
setDT(df)[, Quest := TimesOrCorrect[DashedOrQuest == "question"], by = .(Subj, ItemNo)] 
df 
#  Subj DashedOrQuest ItemNo TimesOrCorrect Quest 
# 1: 1  dashed 243   859  1 
# 2: 1  dashed 243   648  1 
# 3: 1  dashed 243   655  1 
# 4: 1  dashed 243   389  1 
# 5: 1  question 243    1  1 
# 6: 1  dashed 244   465  0 
# 7: 1  dashed 244   844  0 
# 8: 1  dashed 244   578  0 
# 9: 1  dashed 244   713  0 
#10: 1  question 244    0  0 
1
library(dplyr) 
df%>%group_by(ItemNo)%>%mutate(Quest=TimesOrCorrect[DashedOrQuest=='question']) 
相关问题