简体   繁体   English

比较R中的两个向量并将结果保存到新向量

[英]Compare two vectors in R and save result to new vector

I need to compare two vectors in R like: 我需要比较R中的两个向量,例如:

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: 它们都具有相同的长度,因此我需要将A与B进行比较并找到最大值并将其保存到新的向量C中,在这种情况下,它将是:

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

how can i do it? 我该怎么做? Thanks in advance 提前致谢

Try this: 尝试这个:

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

This is what pmax (parallel max) is for: 这是pmax (并行最大)的用途:

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 . 如果向量在listdata.frame ,则可以使用do.call将列表传递给pmax

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM