【发布时间】:2020-03-19 18:24:30
【问题描述】:
我希望从时间序列数据中提取前 n 个最大值,例如对于 Jan,显示前 n 个值;对于 2 月,显示前 10 个值等。
#Data set example
df <- data.frame(
variables = rep(c("height", "weight", "mass", "IQ", "EQ"), times = 12),
month = rep(1:12, each = 5),
values = rnorm(60, 3, 1)
)
head(df, 10)
variables month values
1 height 1 1.859971
2 weight 1 3.985432
3 mass 1 4.755852
4 IQ 1 1.507079
5 EQ 1 2.816110
6 height 2 2.394953
7 weight 2 3.256810
8 mass 2 3.776439
9 IQ 2 3.038668
10 EQ 2 3.540750
尝试每月提取前 3 个值,但出现此错误:
df %>%
group_by(month) %>%
summarise(top.three = top_n(3))
Error in UseMethod("tbl_vars") :
no applicable method for 'tbl_vars' applied to an object of class "c('double', 'numeric')"
有人可以建议吗?谢谢。
【问题讨论】:
-
这会提取每个月的前 3 个值
df %>% group_by(month) %>% top_n(3),如果您需要每个变量的最高值,请将其添加到您的分组语句中。
标签: r dplyr time-series