繁体   English   中英

R:如何创建一个基于另一列某些值的新列?

[英]R: How to create a new column with values based on certain values of another column?

我有一个带有几个变量的数据框:

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

我想做的是创建一个新列“ Quest”,以便对于每个ItemNo,都将在TimesOrCorrect中输入DashedOrQuest中“ question”值的数字。 换句话说,它应该看起来像这样

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中做到这一点吗? 提前致谢!

library(dplyr)
df%>%group_by(ItemNo)%>%mutate(Quest=TimesOrCorrect[DashedOrQuest=='question'])

我们可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM