2017-01-06 36 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']) 
相關問題