简体   繁体   中英

Check if a character exists in a specific group and create a new column in R

Thank you in advance for your time reading this post. I have a data.frame that looks like this

time   offspring
 1         1
 1         2
 2         1
 2         5
 3         1
 3         4

and I would like to check if the offspring of every time point match the offspring of the last time point. To be more explicit I would like to see if the offspring of the time point 1 and time point 2 are present in the timepoint 3.

When this is the case, then I would like to assign the offspring with the value 1 in a new column and when not with the value 0.4. For example

time   offspring  alpha
 1         1       1
 1         2       0.4
 2         1       1
 2         5      0.4
 3         1       1
 3         4       1

Any help and comment are highly appreciated.

One dplyr option could be:

df %>%
 group_by(offspring) %>%
 mutate(alpha = pmax(0.4, all(1:3 %in% time)))

   time offspring alpha
  <int>     <int> <dbl>
1     1         1   1  
2     1         2   0.4
3     2         1   1  
4     2         5   0.4
5     3         1   1  
6     3         4   0.4

If cases that are only present at time period three should be also treated as ones:

df %>%
 group_by(offspring) %>%
 mutate(alpha = pmax(0.4, all(1:3 %in% time) | unique(time) == 3))

   time offspring alpha
  <int>     <int> <dbl>
1     1         1   1  
2     1         2   0.4
3     2         1   1  
4     2         5   0.4
5     3         1   1  
6     3         4   1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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