[R] Using a mathematical expression in sapply() XXXX
peter dalgaard
pdalgd at gmail.com
Wed Jan 4 20:08:54 CET 2012
On Jan 4, 2012, at 16:32 , David Winsemius wrote:
>
> On Jan 4, 2012, at 9:17 AM, peter dalgaard wrote:
>
>>
>> On Jan 4, 2012, at 14:57 , Milan Bouchet-Valat wrote:
>>
>>> Le mercredi 04 janvier 2012 à 08:41 -0500, Dan Abner a écrit :
>>>> Hello everyone,
>>>>
>>>> I have the following call to sapply() and error message. Is the most
>>>> efficient way to deal with this to make sum(!is.na(x)) a function in a
>>>> separate line prior to this call? If not, please advise.
>>>>
>>>> N.Valid=sapply(x,sum(!is.na(x)))
>>>> Error in match.fun(FUN) :
>>>> 'sum(!is.na(x))' is not a function, character or symbol
>>> You can use this:
>>> sapply(x, function(x) sum(!is.na(x)))
>>>
>>> But, if you can convert x to a matrix, it would be faster and shorter to
>>> check for NAs beforehand, and use apply():
>>> x <- matrix(c(1, 2, NA, 3, NA, 4), 2)
>>> apply(!is.na(x), 2, sum)
>>
>> Just for completeness: You might also do
>>
>> sapply(lapply(x, is.na), sum)
>
> I thought from context that the sum of negation of is.na was what was desired, since the negation operator was used and the name of the results was N.Valid.
Oops. Yes.
> So consider substituting the existing function, complete.cases in place of is.na:
>
> sapply(lapply(x, complete.cases), sum)
Yes. I suppose Negate(is.na) would just be being silly. Unless x is a list of data frames or something...
Picking up on Milan's note, notice that if x is a data frame, then conversion to matrix is automatic and, e.g.
> apply(!is.na(airquality), 2, sum)
Ozone Solar.R Wind Temp Month Day
116 146 153 153 153 153
works fine.
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list