When using "apply", can I return just one value of a function?

Viewed 144

I'm not familiarized with the apply in R. When I try to return just one value of the function, it can't return that. This problem might be very easy to solve, but I'm not getting to it.

For example, when I try with the function sens.slope (From package trend ), it won't return just one numeric value.

> e <- matrix(1:50, nrow = 5)
> apply(e,2, sens.slope$estimates)
Error in sens.slope$estimates : 
  object of type 'closure' is not subsettable 

Is there another solution? Thank you!

1 Answers

apply needs a function as an argument. sens.slope is a function, but sens.slope$estimates isn't function, it's confusing the name of the function with the result. The usual way to do this is to make an anonymous function that returns only the piece you want:

apply(e, 2, function(x) sens.slope(x)$estimates)
# [1] 1 1 1 1 1 1 1 1 1 1

An anonymous function is a just a regular function that we don't bother to save and name because we don't expect to use it again.

We could alternately write it as below, which might be nice if we saw potential for using this function again. The above way is much shorter if this is a one-time thing.

sens.slope.est.only <- function(x) {
  slope <- sens.slope(x)
  est <- slope$estimates
  return(est)
}

apply(e, 2, sens.slope.est.only)
Related