Still quite new to R and I would like to identify the biggest value of a variable within a group when an other variable is postive/negative. Specifically, if l_diff<0, I would like to find the biggest value of t in each group when pos_n<0. If l_diff>0, I would like to find the biggest value of t in each group when pos_p>0. Example data:
l_diff <- c(-1,-1,-1,-1,-1,-1,1,1,1,1,1)
pos_n <- c(2,2,1,-4,-2,-2,2,1,-5,4,8)
pos_p <- c(3,4,-5,6,-7,2,-3,3,2,1,4)
t <- c(5,7,3,1,6,2,7,5,3,2,1)
group <- c(1,1,1,1,1,1,2,2,2,2,2)
db <- data.frame(cbind(l_diff,pos_n, pos_p, t, group))
Desired output:
cmax<- c(6,6,6,6,6,6,5,5,5,5,5)
I tried the following:
db<-db %>%
group_by((group)) %>%
mutate(ifelse(l_diff<0, t1 = max(t[pos_n<0], ifelse(l_diff>0, t1 = max(t[pos_p >0])))))
But I get the following error:
Error: Problem with
mutate()input..1. x unused argument (t1 = max(t[pos_n < 0], ifelse(l_diff > 0, t1 = max(t[pos_p > 0])))) i Input..1isifelse(...). i The error occurred in group 1: (group) = 1.
Any idea what may be wrong or any other suggestions?
With
ifelse, we need to place the assignment outside, similarly, all the arguments in theifelseusage must be presentHere, the
nowas not found in the nested secondifelse. It is not an issue if we usecase_whenas by default theTRUE ~ NA-output