简体   繁体   English

R:根据条件为组赋值

[英]R: Assign value to group based on condition

I have a problem by assign a value to a group.通过为组分配值,我遇到了问题。 For example my data look like:例如我的数据看起来像:

example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,2,3,4,1,5,1,2,3,4))

Now I would like to generate a new variable true which assigns a 1 to the whole group ( ID ) if any AL contains a 1 such that the resulting dataframe looks like:现在我想生成一个新变量true ,如果任何 AL 包含 1 则将 1 分配给整个组( ID ),这样生成的 dataframe 看起来像:

example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,1,3,4,1,5,1,2,3,4), "true" = c(1,1,1,1,0,0,0,1,1,1,1,0,0))

It would be great if someone had an idea on how to do this.如果有人知道如何做到这一点,那就太好了。

library(tidyverse)
example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,2,3,4,1,5,1,2,3,4))

example.frame %>% 
  group_by(ID) %>% 
  mutate(true=length(AL[AL==1])) %>%  #number of 1s per group 
  mutate(true=case_when(true>0 ~ 1,  #if larger than 0 => 1
                        TRUE ~ 0))
#> # A tibble: 13 x 3
#> # Groups:   ID [4]
#>       ID    AL  true
#>    <dbl> <dbl> <dbl>
#>  1     1     1     1
#>  2     1     1     1
#>  3     1     2     1
#>  4     1     4     1
#>  5     2     2     0
#>  6     2     3     0
#>  7     2     4     0
#>  8     3     1     1
#>  9     3     5     1
#> 10     3     1     1
#> 11     3     2     1
#> 12     4     3     0
#> 13     4     4     0

Created on 2020-12-02 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 12 月 2 日创建

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

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