[R] Conditional statement used in sapply()

Steven McKinney smckinney at bccrc.ca
Thu Aug 14 00:29:14 CEST 2008



> -----Original Message-----
> From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org]
> On Behalf Of Altaweel, Mark R.
> Sent: Wednesday, August 13, 2008 3:03 PM
> To: r-help at r-project.org
> Subject: [R] Conditional statement used in sapply()
> 
> Hi,
> 
> I have data stored in a list that I would like to aggregate and
perform
> some basic stats. However, I would like to apply conditional
statements so
> that not all the data are used.  Basically, I want to get a specific
> variable, do some basic functions (such as a mean), but only get the
data
> in each element's data that match the condition. The code I used is
below:
> 
> > result<-sapply(res, function(.df) {   #res is the list containing
file
> data
> + if(.df$Volume>0)mean(.df$Volume)  #only have the mean function
calculate
> on values great than 0
> + })
> 

You probably want something such as
result<-sapply(res, function(.df) {  mean(.df$Volume[.df$Volume>0]) })  

HTH
Steve McKinney

> 
> I did get a numeric output; however, when I checked the output value
the
> conditional was ignored (i.e. it did not do anything to the
calculation)
> 
> I also obtained these warning statements:
> 
> Warning messages:
> 1: In if (.df$Volume > 0) mean(.df$Volume) :
>   the condition has length > 1 and only the first element will be used
> 2: In if (.df$Volume > 0) mean(.df$Volume) :
>   the condition has length > 1 and only the first element will be used
> 
> Please let me know what am I doing wrong and how can I apply a
conditional
> statement to the sapply function.
> 
> Thanks
> 
> Mark
> 
> ______________________________________________
> 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