cfosser
cfosser

Reputation: 175

R why does do.call not match a direct calculation?

In the process of doing something more complicated, I've found the following: If I use do.call converting a numeric vector to a list, I am getting a different value from the applied function and I'm not sure why.

x <- rnorm(30)
median(x) # -0.01192347

# does not match:
do.call("median",as.list(x))  # -1.912244

Why?

Note: I'm trying to run various functions using a vector of function names. This works with do.call, but only if I get the correct output from do.call.

Thanks for any suggestions.

Upvotes: 0

Views: 138

Answers (1)

joran
joran

Reputation: 173577

So do.call expects the args argument to be a list of arguments, so technically we'd want to pass list(x = x):

> set.seed(123)
> x <- rnorm(10)
> median(x)
[1] -0.07983455
> do.call(median,list(x = x))
[1] -0.07983455
> do.call(median,as.list(x))
[1] -0.5604756

Calling as.list on the vector x turns it into a list of length 10, as though you were going to call median and pass it 10 separate arguments. But really, we're passing just one, x. So in the end it just grabs the first element of the vector and passes that to the argument x.

Upvotes: 1

Related Questions