我想过滤数据表并对过滤后的数据表的每一行执行一些计算。我知道我可以通过 2 个步骤完成此操作:1) 过滤数据表并分配给新对象,2) 在已过滤的表上计算我需要的内容。
但是有没有办法一步做到这一点? IE。一种在 by=
参数中使用过滤表的行数的方法?
我的样本数据:
test <- data.frame(min_date = c("2017-08-03", "2017-09-10", "2017-10-03"),
max_date = c("2017-08-10", "2017-10-12", "2017-11-01"),
group = c("g1", "g2", "g1"), loc = c("1", "2", "1"))
我只想过滤组
g1
并为每条记录在 min_date 和 max_date 之间的每一天添加新行。没有过滤,我会这样做:
dt <- setDT(test)[ , list(group = group, loc = loc,
min_date = min(as.Date(min_date)),
max_date = max(as.Date(max_date)),
loc = loc,
date = seq(as.Date(min_date),
as.Date(max_date),
by = "day")),
by = 1:nrow(test)]
通过过滤,如果我知道过滤后的行数:
dt <- setDT(test)[group == "g1", list(group = group, loc = loc,
min_date = min(as.Date(min_date)),
max_date = max(as.Date(max_date)),
loc = loc,
date = seq(as.Date(min_date),
as.Date(max_date),
by = "day")),
by = 1:2]
问题是,我不能使用硬编码的行数和
nrow(test)
以及 .N
返回原始数据集的行数。进行过滤然后按操作分组的最快方法是什么?过滤,分配给新对象并通过唯一(也是最好的)方式执行分组吗?
谢谢!
最佳答案
将评论中的三个建议移至答案,您可以尝试以下方法之一(按 nchar
排序,而不是按性能排序,因为我不知道您必须重新创建可比较的大样本数据以测试性能的条件):
test[group == "g1", thing_you_want_to_do, test[group == "g1", .I]]
test[group == "g1", thing_you_want_to_do, seq_len(test[group == "g1", .N])]
test[, nrows := .N, group][group == "g1", thing_you_want_to_do, by = seq_len(nrows[1])]
显然,将
thing_you_want_to_do
替换为您的实际计算。关于r - 如何对已过滤数据表上的每一行进行过滤和分组操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46263238/