Finding maximum of two vectors without a loop?

2019-03-05 15:46发布

问题:

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?

回答1:

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.



回答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.