[R] matrix manipulation with a for loop

antonio rodriguez antonio.raju at gmail.com
Wed Nov 1 18:51:52 CET 2006


Hi,

Having a matrix F.zoo (6575,189) with NA's in some columns I'm trying to 
extract from each column the percent of days within an specific range, 
so I've wrote this procedure:

length(subset(F.zoo[,86],(F.zoo[,86]>=5) & (F.zoo[,86]<= 
9)))/(length(F.zoo[,86])-length(subset(F.zoo[,86],is.na(F.zoo[,86]))))*100

But to do this for each column (189) is pretty hard, so I want to write 
a function in order to perform this automatically, such I have the 
percent value corresponding to a specific column. I' tried these two 
formulas but I can't get it. I think the problem is how to set the 
initial values for the loop:

Formula1:

nnn<-function(x){for (i in F.zoo[,i]){
    print(length(subset(F.zoo[,i],(F.zoo[,i]>=5) & (F.zoo[,i]<= 
9)))/(length(F.zoo[,i])-length(subset(F.zoo[,i],is.na(F.zoo[,i]))))*100)
}
}

Formula 2:

H<-t(matrix(1,189))

nnn<-function(x){for (i in col(H){
    print(length(subset(F.zoo[,i],(F.zoo[,i]>=5) & (F.zoo[,i]<= 
9)))/(length(F.zoo[,i])-length(subset(F.zoo[,i],is.na(F.zoo[,i]))))*100)
}
}

Thanks,

Antonio



More information about the R-help mailing list