![](/img/trans.png)
[英]How to count by group and find if at least one observation meets a criteria?
[英]Changing value of rows that belong to same group and at least one observation in the group meets a condition with dplyr
假設我有這個 dataframe:
df <- data.frame(Sequence_ID = c(100,100,100,100,101,101,101,101,102,102,102,102,103,103,103,103), Success = c(1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1))
如果任何具有相同 Sequence_ID 的行在 Success 列中有 1,那么我希望該組中的所有行在成功列中有 1。
我可以使用以下代碼獲得我想要的 output:
for(i in 1:nrow(df)){
x <- df$Sequence_ID[i]
if (any(df$success[df$Sequence_ID == x] == 1)){
df$success[df$Sequence_ID == x] <- 1
}
}
我想知道在 dplyr 中是否有辦法做到這一點。 提前致謝
library(dplyr)
df %>%
group_by(Sequence_ID) %>%
mutate(
Success = as.integer(any(as.logical(Success)))
)
訣竅:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.