b_takhel
b_takhel

Reputation: 55

Create maximum value for each group

I am trying to classify the temp variable into different classes in such a way that Dur>5.
Further, I want to find the maximum value for each group as shown in expected outcome.

Dur=c(2.75,0.25,13,0.25,45.25,0.25,0.25,4.25,0.25,0.25,14)
temp=c(2.54,5.08,0,2.54,0,5,2.54,0,2.54,0,2.54)
df=data.frame(Dur,temp)

Expected Outcome:

group=c(1,1,1,2,2,3,3,3,3,3,3)
Colnew=c(5.08,5.08,5.08,2.54,2.54,5,5,5,5,5,5)
(output=data.frame(df,group,Colnew))

Upvotes: 1

Views: 69

Answers (1)

akrun
akrun

Reputation: 887891

We create a grouping variable by taking the cumsum of logical vector, then get the max of 'temp'

library(dplyr)
df %>%
   group_by(group = as.integer(factor(lag(cumsum(Dur > 5), default = 0)))) %>%
   mutate(Max = max(temp))
# A tibble: 11 x 4
# Groups:   group [3]
#    Dur  temp group   Max
#   <dbl> <dbl> <int> <dbl>
# 1  2.75  2.54     1  5.08
# 2  0.25  5.08     1  5.08
# 3 13     0        1  5.08
# 4  0.25  2.54     2  2.54
# 5 45.2   0        2  2.54
# 6  0.25  5        3  5   
# 7  0.25  2.54     3  5   
# 8  4.25  0        3  5   
# 9  0.25  2.54     3  5   
#10  0.25  0        3  5   
#11 14     2.54     3  5   

Upvotes: 2

Related Questions