0
votes

My data frame (df) is:

Year Site1 Site2 Site3   
2000 2 4 5  
2001 2 5 45  
2002 4 4 56  
2003 23 67 45  
2004 4 4 34  
2005 3 56 34   
2006 67 12 24

And I want to calculate the mean of the three sites from certain time windows. The periods would be: a)from 2000 to 2006, b) from 2001 to 2006, c) from 2002 to 2006 and d) from 2000 to 2004

The code I used for period "a" is the following:

P <- cbind(df[,2:4]
mean_a <- aggregate(P ~ df[1:7,], mean)

and I get the following:

Error in aggregate.data.frame(as.data.frame(x), ...) : 'by' must be a list

2

2 Answers

2
votes

Something like this?

> ix=list(2000:2006,2001:2006,2002:2006,2000:2004)
> lapply(ix,function(x){colMeans(subset(dat,Year%in%x,select=-c(Year)))})

[[1]]
   Site1    Site2    Site3 
15.00000 21.71429 34.71429 

[[2]]
   Site1    Site2    Site3 
17.16667 24.66667 39.66667 

[[3]]
Site1 Site2 Site3 
 20.2  28.6  38.6 

[[4]]
Site1 Site2 Site3 
  7.0  16.8  37.0
0
votes
library(dplyr)
library(purrr)

fy_1 <- c(2000:2006)
fy_2 <- c(2001:2006)
fy_3 <- c(2006:2006)
fy_4 <- c(2000:2004)

fy <- list(fy_1, fy_2, fy_3, fy_4)

map(.x = fy, ~ foo %>%
  filter(Year %in% .x) %>%
  select(-Year) %>%
  colMeans())