[R] Nested for loop help please.

William Dunlap wdunlap at tibco.com
Sat Jan 11 23:08:54 CET 2014


> > for(count in 1:length(pick.a)){
> + for(count in 1:length(pick.d)){
> + ts=sum(t(m.sham,pick.a[count],pick.d[count]))

The variable 'count' in the inner loop is overwriting the value
of 'count' set in the outer loop.  Use different names in
the different loops.
   for(count.a in seq_along(pick.a)){
       for(count.d in seq_along(pick.d)){
           FUN(pick.a[count.a], pick.d[count.d])

(I wrote 'FUN' because the t() function is misused in the example.)

Bill Dunlap
TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Mathew Nagendran
> Sent: Saturday, January 11, 2014 10:46 AM
> To: r-help at r-project.org
> Subject: [R] Nested for loop help please.
> 
> Hi all I am relatively new to R. I am trying to create a nested for loop but i keep getting
> an error message (unused argument). Can someone help me find out where I am goign
> wrong?
> 
> > m.control=c(1.45,9.40,9.96,4.2,1.86,0.2)
> > m.sham=c(3.39,23.94,23.62,10.08,2.99,1.09)
> >
> > t.control=function(m, a){(1-exp(-a*m))}
> > t.sham=function(m, a, d){(1-exp(-a*(1-d)*m))}
> >
> > t.ratio=function(ts, tc){(ts/tc)}
> >
> > pick.a=seq(0.01,2,by=0.01) #set of a values defined
> > pick.d=seq(0.01,1,by=0.01) #set of d values defined
> >
> > output=array(NA,c(length(pick.a), length(pick.d))) #define array for Ts/Tc ratios. a
> values (0.01-2) in column 1 and d values (0.01-1) in the other columns.
> >
> > for(count in 1:length(pick.a)){
> + for(count in 1:length(pick.d)){
> + ts=sum(t(m.sham,pick.a[count],pick.d[count]))
> + tc=sum(t(m.control,pick.a[count]))
> + output[count,2]= (ts/tc)
> + }
> + print(output)
> + }
> Error in t(m.sham, pick.a[count], pick.d[count]) :
>   unused argument(s) (pick.a[count], pick.d[count])
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list