web_1920
web_1920

Reputation: 23

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:

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.

Upvotes: 1

Views: 1342

Answers (1)

zoowalk
zoowalk

Reputation: 2134

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)

Upvotes: 1

Related Questions