1
fname = file.choose()
two = read.csv(fname.header=T)

rec = two$Receipt
del = two$Delivery
date = two$Date
net = rec-del

yrec = matrix(rec,nrow=365,ncol=4,byrow=F)
ydel = matrix(del,nrow=365,ncol=4,byrow=F)
ynet = matrix(net,nrow=365,ncol=4,byrow=F)
yrecsum = 0
yrecavg = 0

for(i in 1:4)
{
   for(j in 1:365)
   {
      yrecsum[i] = yrecsum[i]+yrec[j,i]
   }
   yrecavg[i] = yrecsum[i]/365
}

So what I have are three matrices of the same size with days in integers (from 1 to 365) on the rows and years integers (from 1 to 4) on the columns. Each matrix is filled in with the data that I'm working with.

I'm trying to find the average of each column for all three matrices and I would like to put those averages in a vector for each matrix.

I've looked around and found some information about the zoo library and chron library and such but I can't get those to work.

Andy Kim
  • 13
  • 2
  • please provide a reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – grrgrrbla Jun 10 '15 at 19:44
  • 1
    Why not skip the loops and just use `colMeans`? Try `colMeans(yrec)` – IRTFM Jun 10 '15 at 19:47

2 Answers2

1
lapply(list(yrec, ydel, ynet), colMeans)

[[1]]
[1] 732.9370 731.9836 705.3808 751.6986

[[2]]
[1] 704.7178 714.2877 735.4822 767.5123

[[3]]
[1] 749.1041 715.4164 711.1425 746.3370

#Data
yrec <- matrix(sample(365*4), ncol=4)
ydel <- matrix(sample(365*4), ncol=4)
ynet <- matrix(sample(365*4), ncol=4)
Pierre L
  • 28,203
  • 6
  • 47
  • 69
0

this should get you started (even though I would convert the matrices to data.frames):

#some sample data
m <- matrix(sample(10000, 365*4),365,4)

# get the mean of all the columns of your matrix
colMeans(m)

if you have 3 matrices and you want to combine the results I would do:

# some sample data:
m1 <- matrix(sample(10000, 365*4),365,4)
m2 <- matrix(sample(10000, 365*4),365,4)
m3 <- matrix(sample(10000, 365*4),365,4)

do.call("cbind", lapply(list(m1,m2,m3), colMeans))
grrgrrbla
  • 2,529
  • 2
  • 16
  • 29