首页 > 解决方案 > 每组中的条件操作

问题描述

我有几组数据,每组中都有一个数字是 7 的倍数。

对于每个组,我想从该倍数中减去第一个值。

可重现的例子:

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

预期结果:

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

你能建议我一种不需要使用任何循环的方法吗?

标签: r

解决方案


您可以得到每个可被 7 整除的数字,group然后用第一个值减去它。

这可以在基础 R 中使用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

您也可以使用dplyr

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

data.table

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

推荐阅读