Reputation: 3088
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.
Upvotes: 2
Views: 602
Reputation: 39858
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
Upvotes: 2