【问题标题】:Time Series: Group_by, Summarize and Top_n [duplicate]时间序列:Group_by、Summarize 和 Top_n [重复]
【发布时间】: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 %&gt;% group_by(month) %&gt;% top_n(3),如果您需要每个变量的最高值,请将其添加到您的分组语句中。

标签: r dplyr time-series


【解决方案1】:

当您使用 summarise 时,它​​会在您的所有列上执行此操作,并且您必须以长度 1 结束。

先按列排序,取前三如何?

df %>% arrange(desc(values)) %>% group_by(month) %>% top_n(wt=values,3)

或者如果您想查看已排序的结果:

df %>% arrange(month,desc(values)) %>% group_by(month) %>% top_n(wt=values,3)

# A tibble: 36 x 3
# Groups:   month [12]
   variables month values
   <fct>     <int>  <dbl>
 1 height        1   5.42
 2 mass          1   3.21
 3 EQ            1   3.19
 4 EQ            2   4.66
 5 weight        2   4.40
 6 IQ            2   3.97
 7 IQ            3   4.73
 8 height        3   3.89
 9 mass          3   3.73
10 IQ            4   3.97

【讨论】:

  • 非常感谢这个解决方案 - 就像一个魅力。因此,如果我正确理解这一点,我的代码中有一部分导致长度大于 1?或许将 Summarize() 与 top_n 一起使用?
  • 在我看来,top_n 不是 summarise-ing 函数,例如 summean,所以 summarise 在这里是多余的。正如@StupidWolf 提到的,传递给summarise 的函数需要返回单个值,而top_n(带有n=3)不返回单个值。
  • 嗨@Desmond,很抱歉回复晚了。所以有两个冲突,1. top_n 必须接受一个 tbl 对象作为输入,所以即使你将它作为 summarise(x=top_n(1)) 提供它也不起作用。 2. 正如 ValeriVoev 上面指出的,summary 期望长度为 1 的结果。
猜你喜欢
  • 2021-09-01
  • 2019-06-08
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
相关资源
最近更新 更多