# Need a short way to graph means and ses from lists of 2 dimensional matrices

This sets up my data frame

means<- list() means[[1]] <- matrix(c(5,4,6,7,8,8,2,3,4), nrow=3, ncol=3) means[[2]] <- matrix(c(11,7,5,7,8,8,4,3,10), nrow=3, ncol=3) ses <- list ( ) ses[[1]] <- matrix(c(0.5,0.4,0.6,0.7,0.8,0.8,0.2,0.3,0.4), nrow=3, ncol=3) ses[[2]] <- matrix(c(0.11,0.7,0.5,0.7,0.8,0.8,0.4,0.3,0.10),nrow=3, ncol=3) names(means)<- c("nameone", "nametwo") colnames(means[[1]])<- c("1", "2", "3") colnames(means[[2]])<- c("1", "2", "3") rownames(means[[1]])<- c("a", "b", "c") rownames(means[[2]])<- c("a", "b", "c")

This is the code to create the graphs which I've done. Basically I'd like a short form way to achieve the same thing it's just too messy and too much typing, maybe a way to avoid the nested looping etc?

dev.off() par(mfrow=c(1,2)) for (j in 1:2){ means1 <- means[[j]] ses1 <- ses[[j]] if (j == 1) title <- "A" else title <- "B" for (i in 1:3){ plot(means1[i,], ylim = c(2, 15), xlim = c(0, 4), xlab = "factor1", ylab = "DV", xaxt = "n", col=i, pch=i, main = title) axis(1, at=1:3, labels=c("1","2","3")) add.bars(means1[i,], ses1[i,], col = i) par(new=TRUE) } if (j == 1) legend (2.5, 14, names(means1[,1]), pch = 1:3, col = 1:3) }

## Answers

It's hard to tell exactly what you were going for but you could avoid the nested loops by converting to data.frames and using ggplot2.

Before making the conversion I would make sure means and ses have the same names:

ses <- Map(function(m, s) { dimnames(s) <- dimnames(m) return(s) }, means, ses)

Then use functions from the reshape2 and plyr packages (both of which are provided by ggplot2) to convert and combine the two matrix lists:

library(ggplot2) library(reshape2) library(plyr) means.df <- melt(means, value.name = "mean") ses.df <- melt(ses, value.name = "se") plot.df <- join(means.df, ses.df) ggplot(plot.df, aes(factor(Var2), mean)) + geom_bar(stat = "identity") + geom_errorbar(aes(ymax = mean + se, ymin = mean - se)) + facet_grid(L1 ~ Var1) + xlab("Factor") + ylab("DV")

Alternatively you could use colors to differentiate the lettered variables:

ggplot(plot.df, aes(factor(Var2), mean, fill = Var1)) + geom_bar(stat = "identity", position = "dodge") + geom_errorbar(aes(ymax = mean + se, ymin = mean - se), position = "dodge") + facet_grid(L1 ~ .) + xlab("Factor") + ylab("DV")