[R] Conditional statement used in sapply()
Altaweel, Mark R.
maltaweel at anl.gov
Thu Aug 14 00:33:22 CEST 2008
Hi,
Yes, that's it. I got the correct results.
Thanks everyone for their help once again. This is a great help board.
Mark
-----Original Message-----
From: Steven McKinney [mailto:smckinney at bccrc.ca]
Sent: Wed 8/13/2008 5:29 PM
To: Altaweel, Mark R.; r-help at r-project.org
Subject: RE: [R] Conditional statement used in sapply()
> -----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