[R] Help understanding behavior of apply vs sapply

Liaw, Andy andy_liaw at merck.com
Tue Mar 28 04:31:10 CEST 2006


I'll give it a shot:

apply() is only a wrapper around a for loop through the requested
dimension(s).  In this case it would run zls() once for each row in m; i.e.,
twice.  The `Value' section of apply() explains what it does if the function
being applied returns vector of length 0.

sapply() is basically lapply() with nice post-processing if possible.  It
doesn't know about m being 2x2, just that it's a vector with four elements,
so it's going to call the function four times, and return a list with the
result of each of those calls.

Andy

From: Seth Falcon
> 
> Hi,
> 
> I was surprised that apply and sapply don't return the same 
> results in the example below.  Can someone tell me what I'm missing?
> 
> 
> > zls <- function(x) character(0)
> > m <- matrix(0, nrow=2, ncol=2)
> > apply(m, 1, zls)
> character(0)
> > sapply(m, zls)
> [[1]]
> character(0)
> 
> [[2]]
> character(0)
> 
> [[3]]
> character(0)
> 
> [[4]]
> character(0)
> 
> 
> 
> 
> 
> 
> > R.version
>                _                                      
> platform       powerpc-apple-darwin8.5.0              
> arch           powerpc                                
> os             darwin8.5.0                            
> system         powerpc, darwin8.5.0                   
> status         alpha                                  
> major          2                                      
> minor          3.0                                    
> year           2006                                   
> month          03                                     
> day            27                                     
> svn rev        37590                                  
> language       R                                      
> version.string Version 2.3.0 alpha (2006-03-27 r37590)
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list