简体   繁体   中英

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

I have a data frame with several variables:

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

What I would like to do is to create a new column "Quest" so that for each ItemNo there will be the number which is in the TimesOrCorrect for "question" value in DashedOrQuest. In other words, it should look like this

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

Any tips how to do that in R? Thanks in advance!

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

We can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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