What's wrong with my nested for loop in R?

87 views Asked by At
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.

2

There are 2 answers

0
grrgrrbla On BEST ANSWER

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))
0
Pierre L On
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)