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?
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?
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.
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.