0

If there are two vectors, say x and y.

for (i in 1:length(x))
   z[i] = max(x[i],y[i])

Can you please help me to perform this without using a loop?

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149

2 Answers2

13

Assuming that the vectors x and y are of the same length, pmax is your function.

z = pmax(x, y)

If the lengths differ, the pmax expression will return different values than your loop, due to recycling.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
2

For completeness sake I include a solution which uses apply:

Z = cbind(x,y)
apply(Z, 1, max)

I don't know how the different solutions compare in terms of speed, but, @JevgenijsStrigins, you could check quite easily.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • I agree, but I added `apply` because it is much more flexible in terms of the functions it can apply. – Paul Hiemstra Dec 30 '12 at 19:16
  • 1
    sure. `library(benchmark); set.seed(101); x <- runif(1000); y <- runif(1000); benchmark(apply(cbind(x,y),1,max),pmax(x,y))` shows that `pmax` is about 40x faster (don't know how much of that is the cost of `cbind()`) – Ben Bolker Dec 30 '12 at 19:17
  • There might be some overhead because of `cbind`, but I cannot imagine that it would lead to a 40 times decrease in speed. – Paul Hiemstra Dec 30 '12 at 19:19