0

I'm always bumping into the problem of wanting to use function's arguments into an apply function. I have looked around but I could not find any suitable answer...

For example

I have a simple matrix like

dput (tab)

> structure(c(108.13, 108.13, 107.7, 107.66, 107.65, NA, NA, 115.56, 
115.5, 115.45, NA, NA, NA, 122.72, 122.66, 124.81, 124.82, 124.87, 
124.91, 124.94, NA, NA, NA, NA, 130.18), .Dim = c(5L, 5L), .Dimnames = list(
    NULL, NULL))

And I want to get the minimum of each column.

I would do something like:

apply (test, 2, min)
> 107.65     NA     NA 124.81     NA

But now let's say I want to skip the NAs.

For the first column, I would do

min (test[,1], min(na.rm = TRUE))
> 107.65

But I cannot use

apply (test, 2, min(na.rm = TRUE))

So, how am I supposed to pass arguments to a function inside apply?

francoiskroll
  • 1,026
  • 3
  • 13
  • 24
  • 5
    `apply(test, 2, min, na.rm = T)` See this http://stackoverflow.com/questions/14427253/passing-several-arguments-to-fun-of-lapply-and-others-apply – ahly Apr 26 '17 at 17:16

1 Answers1

-2

We can use a vectorized colMins from matrixStats

library(matrixStats)
colMins(tab, na.rm = TRUE)

When we are not sure about how to use the arguments, anonymous function call can be used

apply(test, 2, function(x) min(x, na.rm = TRUE))

Or otherwise as @ahly suggested

akrun
  • 874,273
  • 37
  • 540
  • 662