【问题标题】:How to calculate summary stats over multiple columns in a dataframe with date/time series?如何使用日期/时间序列计算数据框中多列的摘要统计信息?
【发布时间】:2021-07-11 17:06:40
【问题描述】:

我有一个数据框,其中第一列是日期/时间序列,其他 9 列是与水温相关的站点。我想计算每列的每月汇总统计信息。我想要的汇总统计数据是,+/- sd temp 的月平均值,每月时间比例 > 20C 和 23C,每月最高温度。这是我的数据的示例 df

# Create a, b, c, d variables
a <- c("06-25-20 08:00:00 AM","06-25-20 08:15:00 AM",
       "06-25-20 08:30:00 AM","06-25-20 08:45:00 AM",
       "07-25-20 08:45:00 AM", "07-25-20 08:45:00 AM",
       "08-25-20 08:45:00 AM", "08-25-20 08:45:00 AM",
       "09-25-20 08:45:00 AM","09-25-20 08:45:00 AM")
b <- c(4,5,8, "N/A", 4,5,"N/A",7,7,6)
c <- c(6,10,8, "N/A", 8,5,"N/A",8,7,2)
# Join the variables to create a data frame
df <- data.frame(a,b,c)
df$a = as.POSIXlt(df$a, format="%m-%d-%y%H:%M:%S", tz = 'EST')

我开始只是尝试获得有效的每月平均值,但对于我的生活,我无法在不编写大量额外代码的情况下让表格也包含标准偏差和所有其他汇总统计信息。这是我用来表示平均值的代码

Monthly_2020Temp = df %>% 
  group_by(a = format(as.Date(a), '%b-%Y')) %>%
  summarise_each(funs( if(length(na.omit(.))>=15)
    mean(., na.rm=TRUE) else NA_real_), 
    b:c)

这是我在添加标准差时尝试使用的代码

Monthly_2020Temp = df %>% 
  group_by(a = format(as.Date(a), '%b-%Y')) %>%
  summarise_each(funs( if(length(na.omit(.))>=15)
    mean(., na.rm=TRUE) else NA_real_), sd(., na.rm=TRUE) else NA_real_), 
    b:c)

但我得到一个错误

Error: unexpected 'else' in:
"  summarise_each(funs( if(length(na.omit(.))>=15)
    mean(., na.rm=TRUE) else NA_real_), sd(., na.rm=TRUE) else"
>     b:c)
Error: unexpected ')' in "    b:c)"

有人可以帮我为我的时间序列数据制作一个漂亮的汇总统计表吗?

【问题讨论】:

    标签: r statistics mean standard-deviation


    【解决方案1】:

    使用 dplyr summarise 时最好将数据转换为“长”格式。以下是帮助您入门的一种可能方法:

    df$b <- as.numeric(df$b)
    df$c <- as.numeric(df$c)
    
    df %>% pivot_longer(-c(a)) %>% 
      mutate(month = lubridate::month(a), year = lubridate::year(a)) %>% 
      group_by(month, year) %>% 
      summarize(avg = mean(value, na.rm = TRUE), sd =    sd(value, na.rm = TRUE))
    

    【讨论】:

    • 如果我希望将值分别用于每一列怎么办?例如,b 列的月平均值是多少?不是 b 和 c 的月平均值。
    • 将“name”变量(由上面的代码作为列生成)添加到 group_by。
    【解决方案2】:
    df$b <- as.numeric(df$b)
    df$c <- as.numeric(df$c)
    
    library(foqat)
    statdf(df)
    #  mean   sd min  25% 50% 75% max integrity
    #b 5.75 1.49   4 4.75 5.5   7   8       0.8
    #c 6.75 2.43   2 5.75 7.5   8  10       0.8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多