【问题标题】:How to do countif in R based on dates如何根据日期在R中做countif
【发布时间】:2021-06-11 13:29:19
【问题描述】:

我的 Excel 文件中有这些数据,如果我在 Excel 中进行计算,它有很多数据要计算。我想计算 1 个月中有多少天的值超过 50。

我想把它变成类似的东西:

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: r countif


【解决方案1】:

另一个选项是 countas.yearmon 来自 zoo - filter 'Value' 大于 50 的行,然后在转换为 yearmon 类后使用 countas.yearmon

library(dplyr)
library(zoo)
df %>% 
   filter(Value > 50) %>%
   count(month_year = as.yearmon(Date)) 

-输出

  month_year n
1   Jan 2010 3
2   Feb 2010 1

数据

df <- structure(list(Date = structure(c(14610, 14611, 14612, 14618, 
14618, 14624, 14641), class = "Date"), Value = c(27, 35, 78, 
88, 57, 48, 99)), class = "data.frame", row.names = c(NA, -7L
))

【讨论】:

    【解决方案2】:

    假设您的数据由下式给出

    df <- data.frame(Date = as.Date(c("1/1/2010", "1/2/2010", "1/3/2010", "1/9/2010", "1/9/2010", "1/15/2010", "2/1/2010"), "%m/%d/%Y"),
                     Value = c(27, 35, 78, 88, 57, 48, 99))
    

    要计算您可以使用的特定值

    library(dplyr)
    
    df %>%
      group_by(month_year = format(Date, "%m-%y")) %>%
      summarise(count = sum(Value > 50))
    

    返回

    # A tibble: 2 x 2
      month_year count
      <chr>      <int>
    1 01-10          3
    2 02-10          1
    

    注意:您的Date 列必须包含日期(如as.Date)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2021-10-07
      相关资源
      最近更新 更多