Finding maximum of two vectors without a loop?

2019-03-05 15:21发布

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?

2条回答
倾城 Initia
2楼-- · 2019-03-05 16:04

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.

查看更多
贪生不怕死
3楼-- · 2019-03-05 16:25

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.

查看更多
登录 后发表回答