[R] Are loops handled differently in newer versions of R?

Don MacQueen macq at llnl.gov
Wed Mar 17 04:30:53 CET 2010


for ( i in seq(nrow(lab8.dat)) )
         p_unadj[i]<-calc.prob.t(lab8.dat[i,2], lab8.dat[i,3])

The first column of lab8.dat is a factor, and you're trying to use it 
as a loop index as if it were an  integer. (Which I would consider 

No, loops are not handled differently, but automatic conversion of 
factors to numeric apparently is.


At 10:53 PM -0400 3/16/10, Michael Rennie wrote:
>Hi gang,
>I'm perplexed- I have some code that uses for() loops that works 
>fine in R version 2.8 on my mac, worked fine in version 2.8 on my 
>old windows machine, but doesn't work in version 2.10 on windows.
>The loop implements a function over a data frame (code is included below).
>In Mac (running version 2.8), the results of the loop are what I expect:
>>  p_unadj
>[1] 0.034939481 0.015743706 0.089287030 0.001098538 0.039290594
>But in Windows (running version 2.10.1), I get a bunch of NA's...
>>  p_unadj
>  A   B      C    D    E
>If I had to guess, I'd say that R v. 2.10 is handling the i in 
>lab8.dat[,1] differently, given that it's keeping the row names in 
>the output for p_unadj... but why would that stop it from applying 
>the function?
>Any thoughts or suggestions are welcome.
>Here's the code...
>#build the dataset
>locn<-c("A", "B", "C", "D", "E")
>n<-c(28, 14, 21, 52, 35)
>corr.r<-c(0.40, 0.63, 0.38, 0.44, 0.35)
>lab8.dat<-data.frame(locn, n, corr.r)
>#write the function
>calc.prob.t<-function(n, r)
>#given a sample size (n) and correlation coefficient (r), returns 
>the probability for that test
>     {
>     df<-n-2
>     t<-(r-0)/(sqrt((1-r2)/df))
>         probt<-2*(pt(t, df, lower.tail=FALSE))
>     probt
>     }
>#try out the function...
>calc.prob.t(lab8.dat$n[1], lab8.dat$corr.r[1])
>#it works.
>#write a loop to implement that function for every correlation in 
>your dataset...
>#all this just built an empty vector to store the results of our loop...
>for ( i in lab8.dat[,1] )
>         p_unadj[i]<-calc.prob.t(lab8.dat[i,2], lab8.dat[i,3])
>#if executed on my Mac, running R v.2.8, this works (and did using 
>2.8 on my old windows machine). Running v. 2.10 in Windows, I get 
>Michael D. Rennie, Ph.D.
>Postdoctoral Fellow, Environmental and Life Sciences Program
>Trent University
>2140 East Bank Drive, DNA Building (2nd Floor)
>Peterborough, Ontario K9J 7B8
>Vox:705.755.2287 Fax:705.755.1559
>R-help at r-project.org mailing list
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

Don MacQueen
Lawrence Livermore National Laboratory
Livermore, CA, USA
macq at llnl.gov

More information about the R-help mailing list