# R: Error when using Aggregate function to compile monthly means into yearly means

Disclaimer: I'm extremely new to R and have been getting by with using google as my professor.

I have a somewhat large collection of monthly values over a period of several years from several different locations. I am attempting to use the aggregate function to calculate the yearly means for each location so that yearly rates of change can be calculated. However, when I run the code

read_csv_filename <- function(filename){
ret$Source <- filename #EDIT ret } import.list <- ldply(filenames, read_csv_filename) by1 <- import.list$$Source by2 <- import.list$$Result by3 <- import.list$Year
Yearly_Mean <- aggregate(import.list, by==list(by1, by2, by3), FUN= "mean")


I get an error like this

> Yearly_Mean <- aggregate(import.list, by==list(by1, by2, by3), FUN= "mean")
Error in by == list(by1, by2, by3) :
comparison (1) is possible only for atomic and list types


I've spent quite a bit of time looking here and elsewhere for similar issues, but haven't found a case that helped me out at all. Any advice on how to fix this (or a completely new, easier method) would be appreciated.

Thanks!

• Please upvote the answer if it helped you. Jan 4, 2020 at 16:38

You can use the group_by() and summarize function from the dplyr package to achieve the above easily:

library(dplyr)

# No need to create b1, b2 and b3
#by1 <- import.list$$Source #by2 <- import.list$$Result
#by3 <- import.list\$Year

# here you want to group by the data based on 'Year' as you mentioned you want the yearly mean and you want to calculate mean of 'Result' right?.

import.list %>%
group_by(Year) %>%
summarize(Mean = mean(Result, na.rm=TRUE))->Final_Output



The above will group_by the data based on Year and calculate mean of Result column.

• Please upvote if the answer helped you. Jan 4, 2020 at 10:33
• I did! I do not have enough reputation for them to be publicly displayed :) Thanks for the help. Jan 6, 2020 at 20:56