R: create new matrix with outcomes from mathematical operations within another matrix through loops -
i trying generate function conducts various mathematical operations within matrix , stores outcomes of these operations in new matrix similar dimensions. here's example matrix (a lot of silly computations in sufficient variability in data)
test<-matrix(1:290,nrow=10,ncol=29) ; colnames(test)<-1979+seq(1,29) rownames(test)<-c("a","b","c","d","e","f","g","h","i","j") test[,4]<-rep(8) test[7,]<-seq(1,29) test[c(3,5,9),]<-test[c(3,5,9),] * 1/2 test[,c(4,6,8,9,10,15,16,18)]<-test[,c(4,6,8,9,10,15,16,18)]*1/3
i want instance able calculate difference between value in (a,1999) , average of 3 values before (a, 1999). needs flexible , every rowname (firm) , every column (year).
the code trying build looks (i guess):
for(year in 1:29) (k in 1:10) qw<-matrix((test[k, year] + 1/3*(- test[k, year-1] - test[k,year -2] - test[k, year-3])), nrow=10, ncol=29)
when run it, code generates matrix value in matrix 1 last calculation (i.e. 20 in example) while every matrix value should stored in qw.
any suggestions on how can achieve (maybe via apply function)?
thanks in advance
you creating matrix qw
in every iteration. each new matrix overwrites previous one. here's how think do, altough didn't know how want handle first 3 years.
qw <- matrix(nrow=10, ncol=29) colnames(qw)<-1979+seq(1,29) rownames(qw)<-c("a","b","c","d","e","f","g","h","i","j") for(year in 4:29){ (k in 1:10){ qw[k, year] <- (test[k, year] + 1/3*(- test[k, year-1] - test[k,year -2] - test[k, year-3])) } } qw
in r, bad idea use loops, since there more efficient functions. here r way of doing this, using package zoo
.
require(zoo) qw <- matrix(nrow=10, ncol=29) colnames(qw)<-1979+seq(1,29) rownames(qw)<-c("a","b","c","d","e","f","g","h","i","j") qw[,4:29] <- test[,4:29]-t(head(rollmean(t(test), 3),-1)) qw
Comments
Post a Comment