根据组

时间:2017-11-27 15:47:27

标签: r dplyr

考虑以下数据框:

ID <- c(1,1,1,2,2,3,3,3,3)
A <- c("No","No","Yes","Yes","Yes","No","No","No","No")
B <- c("Yes","Yes","Yes","Yes","Yes","No","No","No","No")
df <- data.frame(ID,A,B)

我想要创建B列,其中至少出现一个&#34;是&#34;在A栏中只得到&#34;是&#34;列B中的每个单独ID的值。我尝试了以下两种方法(我觉得我几乎就在那里):

library(dplyr)
df <- df %>% 
  group_by(ID) %>% 
  mutate(B1=ifelse(A == "Yes", "Yes", "No")) # B1 is the new column for comparison

不幸的是,它提供了与A

相同的列

df2 <- transform(df, B1= ave(A, ID, FUN=function(x) x[A == "Yes"]))

会产生错误消息:

1:在x [...] < - m中:   要替换的项目数量不是替换长度的倍数

非常感谢帮助。

0 个答案:

没有答案