[R] help with for loop

Steve Lianoglou mailinglist.honeypot at gmail.com
Sat Sep 12 01:12:22 CEST 2009


Hi,

On Sep 11, 2009, at 6:35 PM, Edward Chen wrote:

> example code:
> P = function(whichday,columns){
> y = which(pvalue[,whichday]<Pvaluetest, arr.ind=TRUE)
> dayarb = raw_urine[y,day1_ind]
> daystand = raw_urine[y,columns]
> meandayxx = geometricmeanRow(dayarb)
> meandayyy = geometricmeanRow(daystand)
> diff = meandayyy - meandayxx
> for(i in 1:nrow(diff)){
> if(diff[i]>0){
> #diffbig = meandayxx<meandayyy
> x_index[i] = which(diff[i]>0)
> x[i] = raw_urine[x_index[i],1]
> dayx[i]= raw_urine[x_index[i],day1_ind]
> dayy[i] = raw_urine[x_index[i],columns]
> jpeg("test 1.jpg",width=800, height = 800)
> matplot(x[i],dayx[i],lwd = 3,pch=1,col = "black",xlim=xbound,  
> ylim=ybound)
> matpoints(x[i],dayy[i],lwd=3,pch=1,col="red")
> dev.off()
> return(length(y),length(x_index),diffbig)}
> else{
> xx_index[i] = which(diff[i]<0, arr.ind=TRUE)
> xx[i] = raw_urine[xx_index[i],1]
> dayxx[i] = raw_urine[xx_index[i],day1_ind]
> dayyy[i] = raw_urine[xx_index[i],columns]
> jpeg("test 2.jpg",width=800, height = 800)
> matplot(xx[i],dayxx[i],lwd = 3,pch=1,col = "black",xlim=xbound,  
> ylim=ybound)
> matpoints(xx[i],dayyy[i],lwd=3,pch=1,col="red")
> dev.off()
> return(length(xx_index))}}}
>
> I ran this code and I got "Error in 1:nrow(diff) : NA/NaN argument".  
> I this
> my problem is with the way I define the i index with the rest of the
> functions.
> Basically I want to run for every row of the matrix that is called the
> "diff". without the for loop, I don't know how to make it work but  
> with it,
> I have a lot of bugs in there that hopefully someone can just point  
> out a
> general direction.

Sorry, I can't put the brainpower into figuring out what the code  
means, but it sounds like you want to run a given function over each  
row of your matrix, yes?

Look at the ``apply`` function, with MARGIN set to 1. Here I'm just  
calling the ``mean`` function over every row of my matrix:

R> m <- matrix(1:100, 10, 10)
R> apply(m, 1, mean)
  [1] 46 47 48 49 50 51 52 53 54 55

Substitute your own function for ``mean``

-steve

--
Steve Lianoglou
Graduate Student: Computational Systems Biology
   |  Memorial Sloan-Kettering Cancer Center
   |  Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact




More information about the R-help mailing list