【问题标题】:Mean of few months for a monthly data in rr 中每月数据的几个月的平均值
【发布时间】:2021-10-13 23:02:41
【问题描述】:

我想找到从 11 月到 3 月的月份的平均值,比如 1982 年 11 月到 1983 年 3 月。然后,对于我的结果,我想要一个带有年份的列,而在另一个列中表示平均值。如果平均值取到 1983 年 3 月,我希望年份与平均值一起显示为 1983 年。 This is how my data looks like.

我希望我的结果看起来像这样。

1983 29.108
1984 26.012

我不太擅长使用 R 包,如果有一个简单的方法可以做到这一点。我真的很感激任何帮助。谢谢。

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example。图片不是共享数据/代码的正确方式。

标签: r mean


【解决方案1】:

这是获取每年 11 月至 3 月平均值的一种方法。

library(dplyr)

df %>%
  #Remove data for month April-October
  filter(!between(month, 4, 10)) %>%
  #arrange the data by year and month
  arrange(year, month) %>%
  #Remove 1st 3 months of the first year and 
  #last 2 months of last year
  filter(!(year == min(year) & month %in% 1:3 | 
         year == max(year) & month %in% 11:12)) %>%
  #Create a group column for every November entry
  group_by(grp = cumsum(month == 11)) %>%
  #Take average for each year 
  summarise(year = last(year),
            value = mean(value)) %>%
  select(-grp)

# A tibble: 2 x 2
#   year  value
#  <int>  <dbl>
#1  1982  0.308
#2  1983 -0.646

数据

如果您以易于复制的可复制格式提供数据,则更容易提供帮助。

set.seed(123)
df <- data.frame(year = rep(1981:1983, each = 12),month = 1:12,value = rnorm(36))

【讨论】:

  • 谢谢。下次我会记住可重现的数据格式。
【解决方案2】:

使用 dplyr

# remove the "#" before in the begining of the next line if dplyr or tidyverse is not installed
#install.packages("dplyr") 

library(dplyr) #reading the library

colnames(df) <- c("year","month","value") #here I assumed your dataset is named df


df<- df%>%
  group_by(year) %>%
  summarize(av_value =mean(value))

【讨论】:

    【解决方案3】:

    您可以使用tidyverse 执行以下操作

    require(tidyverse)
    
    year <- rep(1982:1984, 3)
    month <- rep(1:12, 3)
    value <- runif(length(month))
    
    dat <- data.frame(year, month, value)
    
    head(dat)
    

    dat 看起来像您的数据

    # A tibble: 3 × 2
       year value
      <int> <dbl>
    1  1982 0.450
    2  1983 0.574
    3  1984 0.398
    

    那么诀窍就是group_bysummarise

    dat %>% 
      group_by(year) %>% 
      summarise(value = mean(value))
    

    这给了你

    # A tibble: 3 × 2
       year value
      <int> <dbl>
    1  1982 0.450
    2  1983 0.574
    3  1984 0.398
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2023-03-26
      • 1970-01-01
      • 2015-07-14
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多