2

I'd like to maximize numbers in a vector and get the results as a new vector

Like this:

w <- 0:10
maximizer <- function(w){
  max(10, w + 5)
}

I'm expecting getting a vector (10,10,10,10,10,10,11,12,13,14,15), but all I'm getting is 15. I know weird ways of fixing this, but I'm sure there must be an easier way...

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
Mondainai
  • 35
  • 2

2 Answers2

4

Instead of max you should use pmax:

maximizer <- function(w) pmax(10, w + 5)
maximizer(0:10)
# [1] 10 10 10 10 10 10 11 12 13 14 15

since

pmax() and pmin() take one or more vectors as arguments, recycle them to common length and return a single vector giving the ‘parallel’ maxima (or minima) of the argument vectors.

while

max and min return the maximum or minimum of all the values present in their arguments

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
0

you could use a for-loop with an ifelse statement albeit not as elegant as the solution posted:

for(i in seq_along(w)){
  w[[i]] <- ifelse(w[[i]]+5 < 10, 10, w[[i]] + 5)
}


[1] 10 10 10 10 10 10 11 12 13 14 15
nycrefugee
  • 1,629
  • 1
  • 10
  • 23