简体   繁体   English

根据嵌套组中的组事件在数据框中生成新列

[英]Generate new column in dataframe, based on group-event in nested groups

I have a dataframe with three "main"-groups (x: 1, 2, 3), three groups within the main-groups (v: 2, 3 or 1) and some events within the main-groups (0 and 1 in y): 我有一个数据框,其中包含三个“主要”组(x:1、2、3),三个主要组(v:2、3或1)和主要组中的一些事件(0和1 Y):

x <- c(1, 1, 1, 2, 2, 3, 3, 3, 3)
v <- c(2, 3, 3, 2, 2, 1, 1, 2, 2)
y <- c(0, 0, 1, 0, 0, 0, 0, 0, 1)
df <- data.frame(x, v, y)
df

> df
  x v y
1 1 2 0
2 1 3 0
3 1 3 1
4 2 2 0
5 2 2 0
6 3 1 0
7 3 1 0
8 3 2 0
9 3 2 1

For example: In group 1 (x = 1) there are two more groups (v = 2 and v = 3), event y = 1 happens in group x = 1 and v = 3. 例如:在组1(x = 1)中,还有另外两个组(v = 2和v = 3),事件y = 1发生在组x = 1和v = 3中。

Now i want to generate a new column z, based on the events in y: if there is any y = 1 in one group, all cases in group v in x should get a 1 for z; 现在,我想基于y中的事件生成一个新的列z:如果一个组中的y = 1,则x中v组中的所有情况都应为z取1; else NA. 不,不。 How can z be generated this way? 如何以这种方式生成z? df should look like: df应该看起来像:

> df
  x v y  z
1 1 2 0 NA
2 1 3 0  1
3 1 3 1  1
4 2 2 0 NA
5 2 2 0 NA
6 3 1 0  1
7 3 1 1  1
8 3 2 0 NA
9 3 2 0 NA

I am grateful for any help. 感谢您的帮助。

Try this: 尝试这个:

library(dplyr)

df %>%
group_by(x, v) %>%
mutate(
z = ifelse(any(y == 1), 1, NA)
)
df %>% group_by(x, v) %>% mutate(z = if(any(y == 1)) 1 else NA)

通过分组后xy ,新列z填充有1 ',如果有任何小号1的在y并与NA的说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM