user3294195 user3294195 - 1 month ago 5
R Question

Return a function object with arguments partially filled

I want to define an R function that uses an existing function, with some arguments filled in. For instance, suppose I want to define a function

meanNA
as follows:

meanNA <- mean(na.rm = TRUE)


The idea is that when I call
meanNA(x, trim = 0)
I will call
mean(x, trim = 0, na.rm = TRUE)
. Is this even possible in R? If so, what's the right way to implement this?

Answer

Just take your example, we can write:

meanNA <- function (...) mean(..., na.rm = TRUE)

Example

x <- c(1:4, NA)
meanNA(x)
# [1] 2.5
Comments