【问题标题】:Extracting counts of a variable grouped at 2 levels提取按 2 个级别分组的变量的计数
【发布时间】:2017-11-26 16:32:29
【问题描述】:

我有按年、月和日标记的天气数据。以下是部分数据:

Date         MinT     Year   Month
1976-01-01   1.1      1976   1
1976-01-02   0.3      1976   1
1976-01-03   1.3      1976   1

所有月份的数据运行时间为 1976:2016。调用这个 TestData。

我可以按如下方式分组和子集(这很笨拙,但那是因为我一直在尝试测试每个步骤)

temp1 <- TestData  %>%
  group_by(Year) 
temp2 <- temp1 %>%
  subset(between(Month, 1, 3)) 
temp3 <- temp2
v1 <- replace(temp3$minT, temp3$minT >-2.0,0)  ### replaces data above the threshold 
temp3["v1"] <- v1 
index1 <- with(temp3, tapply(X = v1, INDEX = Year, FUN = sum)) ##       sums the month  1-3-2 degree values
index2 <- with(temp3, tapply(X = v1, INDEX = Year, FUN = length)) ## counts the number of items in each year for the selected period.

index2 给了我每个月的天数。我可以使用index1 和 2 创建“本月天气”索引。

我想要的是能够计算所有低于 -2(或其他)的天数,从而获得每个月的可比严重性指数。

v1 分配是必要的,因为如果我使用 rle 来计算实例数,某些月份的实例数将为零,并且它们会从最终计数中下降,这意味着针对 minTyear 和 @ 的索引编译表987654329@ 具有 R 不喜欢的不同长度的索引向量。我已经尝试将rle 作为index2 分配中的乐趣,但这不会让我达到日数。在该赋值 (index3) 中使用具有长度的范围值也是如此。

没有为每年生成一张迷你表,我被困住了。有人有什么建议吗?

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    我猜summarise 是您正在寻找的功能。像这样的东西(不同的数据,相同的原理):

    library(latticeExtra)
    
    threshold <- 40
    
    SeatacWeather %>%
      group_by(year, month) %>%
      filter(min.temp < threshold) %>%
      summarise(days_below_threshold = n())
    

    【讨论】:

    • 在我的数据上尝试这个我得到一个错误“没有适用于 'group_by_' 的方法应用于类“c('double', 'numeric')”的对象”
    • 你可以试试TestData$Year &lt;- factor(TestData$Year)。否则我们可能需要更多信息。
    • 谢谢!在我读到这篇文章之前,我昨晚半夜想到了这个。我所做的是将 temp1 声明为数据框。这允许 group_by 工作!然后阈值过滤器段产生天数。再次感谢您!
    猜你喜欢
    • 2013-08-31
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多