1
$\begingroup$

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 <- read.csv(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!

$\endgroup$
1
  • $\begingroup$ Please upvote the answer if it helped you. $\endgroup$ Commented Jan 4, 2020 at 16:38

1 Answer 1

0
$\begingroup$

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

library(dplyr)
import.list <- ldply(filenames, read_csv_filename)

# 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.