我在R中嵌套for循环有什么问题?

时间:2015-06-10 19:41:43

标签: r for-loop matrix average moving-average

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
}

所以我所拥有的是三个相同大小的矩阵,行上的整数天数(从1到365)和列上的年份整数(从1到4)。每个矩阵都填写了我正在使用的数据。

我试图找到所有三个矩阵的每列的平均值,我想将这些平均值放在每个矩阵的向量中。

我环顾四周,发现了一些关于动物园图书馆和chron图书馆等的信息,但我无法让它们发挥作用。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

这应该让你入门(即使我将矩阵转换为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)

如果你有3个矩阵,并且你想要结合我将要做的结果:

# 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))
相关问题