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

``````fname = file.choose()

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
}
``````

2 个答案:

``````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)
``````

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

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

``````# 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条回复