【发布时间】:2017-02-10 00:40:37
【问题描述】:
请告诉我正确的“r”方式。
我有 5 个地点。每天每个位置都会有 0 或 2 个值。我想按天获得可能的位置组合。下面的代码有效,但我认为它不是很好。有一个更好的方法吗?我尝试了许多不同的应用、聚合、熔化、铸造等变体。但这就是我要做的全部工作。
请注意,在我的示例数据中,每个位置每天都有 2 个读数。但实际上,一个位置每天会有 0 或 2 个读数,因此每天的组合可能会有所不同。
d1 = rep(seq(as.Date("2015-01-01"), as.Date("2015-01-10"), by = "days"), each = 10)
v1 = round(runif(100, -300, 300))
results =
data.frame(
Date = d1,
Location = c(1:5),
Value = v1
)
dates = unique(lapply(results$Date, function(x) as.Date(x)))
process = function(d, c) {
x = results[(results$Date == d & results$Location %in% c), ]
print(x)
}
for (i in 1:length(dates)){
results.sub = results[as.Date(results$Date) == dates[i], ]
loc = unique(results.sub$Location)
for (m in 1:length(loc)){
combos = combn(loc,m)
for (c in 1:ncol(combos)){
process(dates[i],combos[,c])
}
}
}
我查看了许多其他 SO 答案,但找不到适合我的情况的答案。
感谢您的帮助。
期望的输出
如果当天报告了位置 1、2 和 3,那么在那一天我需要以下所有组合:
1
2
3
1 2
1 3
2 3
1 2 3
解决方案
在Combinations by group in R找到解决方案:
library(dplyr)
results %>% group_by(Date) %>% do(data.frame(t(combn(unique(.$Location), 5))))
这不是一个完整的解决方案,因为它只解决组合中的 n 个项目,而不是 n 的所有可能性。但这与下面的答案应该很接近了。
【问题讨论】:
-
我可能错了,但试试这个:
lapply(split(results, results$Date), function(x) split(x, x$Location ) )。让我知道它是否有效 -
@Sathish,这不是我想要的,但它确实可能帮助我迈出了下一步。我已在问题中添加了所需输出的示例。