Mka
Mka

Reputation: 13

Compare two vectors in R and save result to new vector

I need to compare two vectors in R like:

A
[1,2,2,2,2,3]

B
[2,3,4,1,1,1]

They both have the same length so i need to compare A with B and find the maximum value and save it to a new vector C, in this case it would be:

C
[2,3,4,2,2,3]

how can i do it? Thanks in advance

Upvotes: 1

Views: 314

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

This is what pmax (parallel max) is for:

A <- c(1,2,2,2,2,3)
B <- c(2,3,4,1,1,1)
C <- pmax(A, B)
# [1] 2 3 4 2 2 3

If your vectors are in a list or data.frame, you can use do.call to pass the list to pmax.

l <- list(A, B)
do.call(pmax, l)

Upvotes: 2

Jilber Urbina
Jilber Urbina

Reputation: 61154

Try this:

> C <- ifelse(A>B, A, B)
> C
[1] 2 3 4 2 2 3

Upvotes: 3

Related Questions