Skip to Content

Working with data frames: collecting results into one data frame in R

In the workspace, I have 48 data frames:

zbp1994f, zbp1994m, zbp1994r
zbp1995f, zbp1995m, zbp1995r
......
zbp2009f, zbp2009m, zbp2009r

In each frame, there is a group variable (say, group). I calculate a statistic (Moran's I) by group for just one data frame, that is zbp1994f:

library(ape)
moranfn <- function(dta) {
    distinv <- -1/as.matrix(dist(cbind(dta$longi, dta$lati)))
    diag(distinv) <- 0
    Moran_result <- data.frame(Moran.I(dta$myvariable, distinv))
}
 
library(plyr)
Moran_result_1994f <- ddply(zbp1994f,"group",moranfn)

This gives me the Moran_result_1994f data frame, which contains the statistics by group.

group stat1 stat2 sd     p-value
g1    0.049 -0.01 0.012  2.55e-06
g2    0.122 -0.05 0.041  2.45e-08
......

My goal is to do the job for all the data frames, and make a panel data set:

group year stat1 stat2 sd p-value
g1    1994 ..... ..... .. .....
g1    1995 ..... ..... .. .....
g1    1996 ..... ..... .. .....
......
g1    2009 ..... ..... .. .....
g2    1994 ..... ..... .. .....
......

I wonder how to loop the initial procedure over the year (1994:2009) and c("f","m","r").