blue-sky
blue-sky

Reputation: 53826

Removing for loop using sapply

As a learning exercise in removing for loops using sapply in my code below I'm attempting to return the minimum of a vector using sapply :

f3 <- function(nv) {
    min(nv)
}

myv = c(1:10)
y <- sapply(myv, f3)
y

As expected instead of applying the min function to entire fector to return 1, the min is calculated for each element in the vector returning 1 2 3 4 5 6 7 8 9 10.

How can I use sapply to process the entire vector, therefore returning 1 ?

Upvotes: 1

Views: 85

Answers (1)

beigel
beigel

Reputation: 1200

You can apply min to the whole vector like so

myv <- 1:10
min(myv)
#> [1] 1

min will return the minimum of any number of arguments you give it. If you've got a more complicated data structure than a vector such as a dataframe and you want the minimum for each column than you might want to use sapply although there are other alternatives. Here's an example of where using sapply might make sense:

mydf <- data.frame(x = 1:10, y = 11:20, z = 21:30)
min(mydf)
#> [1] 1
sapply(mydf, min)
#>  x  y  z 
#>  1 11 21

Upvotes: 4

Related Questions