简体   繁体   中英

R: argument of function called by another function (dcast.data.table)

I am using the function dcast.data.table, which takes as argument a summarizing function like, for example, sum or mean. My data contain entries "NA", which I want mean to ignore, so I would like to add na.rm as an argument of mean. What syntax can I use?

Here is what I can do successfully:

> library("data.table")
> library("reshape2")
> DT = data.table(x=rep(c("a","b"),each=5), y=c(1,2), v=c(1:7,NA,NA)) # created as an example
# tabulate the mean value of v for each x-y combination:
> dcast.data.table(DT, x~y,fun = mean, value.var = 'v')
   x  1  2
1: a  3  3
2: b NA NA

I would like to pass the argument na.rm to the function mean being used inside dcast.data.table, is there any way to do this?

You can encapsulate mean this way: function(x){mean(x, na.rm=T)}

This way, your code would become:

library("data.table")
library("reshape2")
DT = data.table(x=rep(c("a","b"),each=5), y=c(1,2), v=c(1:7,NA,NA))
myMean = function(x){mean(x, na.rm=T)}
dcast.data.table(DT, x~y,fun = myMean, value.var = 'v')

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM