Reputation: 441
For each combination of my variables simulation
and iteration
, I would like to
group "a"
had the highest value of rand1
, as well
as rand2
,group "a"
tied with another group based on rand1
, as well as rand2
Some sample df (with hard coded values for rand1
and rand2
for reproducibility:
df = crossing(simulation = 1:3,
iteration = 1:3,
group =c("a","b","c")) %>%
mutate(rand1 = c(6,2,2,6,4,6, sample(6,21,replace=T)), # roundabout way to get the same head of df as in the example, forgot to use set.seed
rand2 = c(4,1,2,5,6,1,sample(6,21,replace=T)))
which gives:
simulation iteration group rand1 rand2
1 1 a 6 4
1 1 b 2 1
1 1 c 2 2
1 2 a 6 5
1 2 b 4 6
1 2 c 6 1
This is what I want my output to look like: top.crit1
is 1 if group a is max, 0 if there is a tie. ties.crit1
lets me know if a was tied for max value with another group, same for top.crit2
and ties.crit2
[not added below to avoid cluttering]
Desired output:
simulation iteration group rand1 rand2 top.crit1 ties.crit1
1 1 a 6 4 1 0
1 1 b 2 1 1 0
1 1 c 2 2 1 0
1 2 a 6 5 0 1
1 2 b 4 6 0 1
1 2 c 6 1 0 1
This is my code so far for only determining the max value (but doesn't take into account ties), it's a bit tedious to determine the maximum value separately for rand1
and rand2
.
df.test = df %>%
group_by(simulation, iteration) %>%
slice(which.max(rand1)) %>%
mutate(top.crit1 = if_else(group=="a",1,0)) %>%
select(-rand2, -rand1, -group) %>%
full_join(., df)
Upvotes: 0
Views: 133
Reputation: 349
This would work if you arrange
to have group a as first row of each group
df %>%
group_by(simulation, iteration) %>%
mutate(top.crit1 = rand1[1] > max(rand1[-1])) %>%
mutate(ties.crit1 = rand1[1] == max(rand1[-1]))
Upvotes: 1