我正在尝试计算两个日期之间低于特定阈值(假设小于或等于 50)的降水量。
基本上,我有一个向量cuts,其中包含我想要计算的日期。我想使用该cuts向量对不同箱中的数据集进行“子集化”,然后计算降雨量小于 50 毫米的事件数量。
我目前正在使用 dplyr 和 for 循环,但没有任何效果。
set.seed(12345)
df = data.frame(date = seq(as.Date("2000/03/01"), as.Date("2002/03/01"), "days"),
precipitation = rnorm(length(seq(as.Date("2000/03/01"), as.Date("2002/03/01"), "days")),80,20))
cuts = c("2001-11-25","2002-01-01","2002-02-18","2002-03-01")
for (i in 1:length(cuts)) {
df %>% summarise(count.prec = if (date > cuts[i] | date < cuts[i+1]) {count(precipitation <= 50)})
}
Run Code Online (Sandbox Code Playgroud)
但我有这个错误消息:
Error: no applicable method for 'group_by_' applied to an object of class "logical"
In addition: Warning message:
In if (c(11017, 11018, 11019, 11020, 11021, 11022, 11023, 11024, :
the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)
这也不起作用:
for (i in 1:length(cuts)) {
df %>% if (date > cuts[i] | date < cuts[i+1])%>% summarise(count.prec = count(precipitation <= 50))
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试:
\n\ndf %>%\n group_by(gr = cut(date, breaks = as.Date(cuts))) %>%\n summarise(res = sum(precipitation <= 50))\nRun Code Online (Sandbox Code Playgroud)\n\n这使:
\n\n# A tibble: 4 \xc3\x97 2\n gr res\n <fctr> <int>\n1 2001-11-25 1\n2 2002-01-01 4\n3 2002-02-18 2\n4 NA 40\nRun Code Online (Sandbox Code Playgroud)\n\n或者正如 @Frank 提到的 - 你可以替换summarise()为tally(precipitation <= 50)
| 归档时间: |
|
| 查看次数: |
1428 次 |
| 最近记录: |