简体   繁体   中英

compare two vectors in r, while and if structure

I have been trying to code this exemple with while loops and if structure but I did not manage to do it. There is always a problem with my synthax.

if x1 >= x2 result = 1 else result = -1

x1 x2 result
 5  7   -1
 3  4   -1
 7  2    1

If anyone manage to get the correct synthax I would be really thankful

I like using dplyr for these kinds of problems. We can tackle this problem in more efficient ways than using loops

# make up some data
library(dplyr)
mydat <- data.frame(x = seq(1:10), y = rev(seq(10:1)))


#calculate result

new_data <- mutate(mydat, result = ifelse(x >= y, "1", "-1"))

There are several ways to get your answers and none of them needs a as must allways be of intrest. 因为必须始终是明智的。 My prefered one would be :

result = (x1>=X2) -(x1<X2)

But this method does the comparison twice and so, is not efficient. You can use its mathematical equivalent one, which is :

result = 2*(x1>=X2) - 1

But if you prefer not to use maths, another pure R way of doing it would be:

result = rep(1,length(x1))
result[x1<X2] = -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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