【发布时间】:2016-09-19 20:35:06
【问题描述】:
我想在 dplyr 中进行分组summarise() 操作,但如果遇到边缘情况,则应用不同的函数。
我有这样的计数数据。浓度和标准差的计算如下:
library(dplyr)
testdata <- data_frame(sample = sort(rep(1:3, 4)),
volume = rep(c(1e-1, 1e-1, 1e-2, 1e-2), 3),
count = c(400, 400, 40, 40, 0, 0, 0, 0, 400, 400, 400, 400))
testdata %>%
group_by(sample) %>%
summarise(concentration = sum(count) / sum(volume),
sd = sqrt(sum(count)))
但是,在进行计算时,仅包含值在 25-250 之间的计数。我可以通过以下方式实现:
testdata %>%
group_by(sample) %>%
filter((count >= 25) & (count <= 250)) %>%
summarise(concentration = sum(count) / sum(volume),
sd = sqrt(sum(count)))
但是样品 2 和 3 没有浓度。
每个组的边缘情况可以通过以下方式计算:
if (all(count <= 25)){
summarise(concentration = 25 / min(volume),
sd = NA)
}
else if (all(count >= 250)){
summarise(concentration = 250 / max(volume),
sd = NA)
}
可以将这种边缘情况集成到summarise() 函数中吗?
理想情况下,我还希望有一个标志来指示一个边缘情况,该情况在所有情况下都返回 result = "OK",但返回的边缘情况除外:
if (all(count <= 25)){
summarise(concentration = 25 / min(volume),
sd = NA,
result = "LOW")
}
else if (all(count >= 250)){
summarise(concentration = 250 / max(volume),
sd = NA,
result = "HIGH")
}
【问题讨论】: