[R] how to break the loop using sapply?

PO SU rhelpmaillist at 163.com
Fri Oct 10 08:12:33 CEST 2014



Is that mean while may be more effient than  for in R? as i know, while and for  are all just functions in R. 
Tks for your suggestion to not use apply that way, but i want to know, if possible, is there any way to break it ?
Actually, there is a additional question:
  x<- c(3,4,5,6,9)
 sapply(x ,function(i){
foo(i)  #do something to each value in x,how can i know the i's index in x?
)}
In my way , i always 
sapply(seq(x),function(i){
foo(x[i])
})
or 
Map( function(i,index){
foo(i)  # through index to know the i's index in x
},x ,seq(x)) 

How you solve the problem? I mean just use apply functions.



--

PO SU
mail: desolator88 at 163.com 
Majored in Statistics from SJTU




At 2014-10-10 13:58:29, "Jeff Newmiller" <jdnewmil at dcn.davis.CA.us> wrote:
>Don't use apply functions if you want to do what you describe. They don't work that way. Use a while control structure.
>
>---------------------------------------------------------------------------
>Jeff Newmiller                        The     .....       .....  Go Live...
>DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
>                                      Live:   OO#.. Dead: OO#..  Playing
>Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
>/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
>--------------------------------------------------------------------------- 
>Sent from my phone. Please excuse my brevity.
>
>On October 9, 2014 10:24:49 PM PDT, PO SU <rhelpmaillist at 163.com> wrote:
>>
>>Dear expeRts,
>>   i  use sapply for loop, and i want to break it when i needed, how to
>>do that?  e.g.
>>
>>sapply( 1:10, function(i) {
>>if(i==5) break and jump out of the function sapply
>>} )
>>
>>I want to do it because i have to loop 1000000 times, but i don't know
>>when it will break, that means, it may need break at i=5 or at i=50000,
>>for the possible of the  last case, i don't use for loop, because it
>>slow(is it right?).
>>So,if you happen to know it ,may you help me?
>>
>>
>>--
>>
>>PO SU
>>mail: desolator88 at 163.com 
>>Majored in Statistics from SJTU
>>______________________________________________
>>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