[英]R/dplyr: Assign value to a group base on one column
我有這個數據集:
test <- data.frame("eventId" = c(rep(1,5), rep(2,3), rep(3,6)),
"commandType" = c(rep("RO",3), rep("RW", 2), rep("RO",7),"RW", "RO"),
"sessionType" = c(rep("RW",5), rep("RO",3), rep("RW",6)))
我想基於commandType
為每個eventId
(組)分配sessionType
。 如果組中出現“ RW”,則將整個組分配為“ RW”。 如果組僅將“ RO”或“ RW”作為commandType
,則sessionType
將與commandType
匹配。
我想這可以在dplyr
完成,但不確定如何實現。 任何幫助將不勝感激! 謝謝!
訣竅是在dplyr
使用group_by
...
test <- test %>%
group_by(eventId) %>%
mutate(sessionType2 = ifelse("RW" %in% commandType, "RW", commandType))
test
eventId commandType sessionType sessionType2
<dbl> <chr> <chr> <chr>
1 1 RO RW RW
2 1 RO RW RW
3 1 RO RW RW
4 1 RW RW RW
5 1 RW RW RW
6 2 RO RO RO
7 2 RO RO RO
8 2 RO RO RO
9 3 RO RW RW
10 3 RO RW RW
11 3 RO RW RW
12 3 RO RW RW
13 3 RW RW RW
14 3 RO RW RW
順便說一句,我還必須在您的數據stringsAsFactors=FALSE
代碼中設置stringsAsFactors=FALSE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.