So, Say I have
l <- list(a=c(1, 2, NA), b=c( 2, 3, NA), c=c(5, NA, 6))
lapply(l, mean)
How do I use lapply where I want the mean function to use the parameter na.rm=TRUE
The following is not working
lapply(l, mean(na.rm=TRUE))
Thanks.
Generally, you can use the ...
to pass other arguments to your function, so the following should work:
l <- list(a=c(1, 2, NA), b=c( 2, 3, NA), c=c(5, NA, 6))
lapply(l, mean, na.rm = TRUE)
In some cases, it might be easier to use an anonymous function, like this:
lapply(l, function(x) mean(x, na.rm = TRUE))
In the second case above, that would be similar to doing something like:
Defining a new mean
function preset with na.rm = TRUE
:
meanNArm <- function(x) mean(x, na.rm = TRUE)
Using that function in lapply
:
lapply(l, meanNArm)
If the function you were dealing with were quite complex, or if you had to do this regularly, then defining your own function might make sense, otherwise, a simple anonymous function (or passing the relevant argument with ...
) would be the more logical approach.
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.