Rel_Ai
Rel_Ai

Reputation: 591

Conditional operations in each group

I have some groups of data and in each group there is one number that is a multiple of 7.

For each group, I want to subtract the first value from that multiple.

Reproducible example:

temp.df <- data.frame("temp" = c(48:55, 70:72, 93:99))
temp.df$group <- cumsum(c(TRUE, diff(temp.df$temp) > 1))

Expected result:

group 1: 49-48 = 1
group 2: 70-70 = 0
group 3: 98-93 = 5

Can you suggest me a way that do not require using any loop?

Upvotes: 0

Views: 45

Answers (2)

akrun
akrun

Reputation: 887168

We can also do

library(dplyr)
temp.df %>% 
   group_by(group) %>% 
   summarise(temp = temp[which.max(!temp %% 7)]  - first(temp))
# A tibble: 3 x 2
#  group  temp
#  <int> <int>
#1     1     1
#2     2     0
#3     3     5

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You can get the number divisible by 7 in each group and subtract it with first value.

This can be done in base R using aggregate.

aggregate(temp~group, temp.df, function(x) x[x %% 7 == 0] - x[1])

#  group temp
#1     1    1
#2     2    0
#3     3    5

You can also do this using dplyr

library(dplyr)
temp.df %>% 
  group_by(group) %>% 
  summarise(temp = temp[temp %% 7 == 0] - first(temp))

and data.table

library(data.table)
setDT(temp.df)[, .(temp = temp[temp %% 7 == 0] - first(temp)), group]

Upvotes: 1

Related Questions