[英]How to create a new column with multiple values based on another column in 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.