r - 每组中的条件操作
问题描述
我有几组数据,每组中都有一个数字是 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
你能建议我一种不需要使用任何循环的方法吗?
解决方案
您可以得到每个可被 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]
推荐阅读
- reactjs - 无法从“node_modules\expo\AppEntry.js”解析“../../App”
- python - 'scrapy: command not found' 即使要求已经满足
- reactjs - 什么是浏览代码库和查找网页源代码的好方法
- lua - 使用“tonumber”后如何将数字再次转换为十六进制?
- mysql - 如何编写通用 SQL 查询以 (YYYY-MM-DD) 形式提取与所有 RDBMS(Oracle、SQL 服务器、MySql、DB2 等等)兼容的日期
- react-native - 最初无法在抽屉导航器中传递道具
- javascript - lodash find 只返回一个结果
- ios - 如何在 Text() 内部的 SwiftUI 中使用 swift-currency 显示货币而不显示“可选”?
- firebase - 云功能的处理 Firebase 实时数据库
- javascript - 如果应用程序中使用的所有函数都以 `async` 为前缀,无论它是否真的是异步的,会发生什么?