[英]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. 我一直在尝试使用while循环和if结构对这个示例进行编码,但是我没有做到这一点。 There is always a problem with my synthax.
我的Synthax总是有问题。
if x1 >= x2 result = 1 else result = -1 如果x1> = x2结果= 1否则结果= -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. 我喜欢将
dplyr
用于此类问题。 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 while loop as
vectorized solutions must allways be of intrest.
有几种方法可以得到答案,但没有一个需要使用while循环,因为
矢量化解决方案必须始终是明智的。 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: 但是,如果您不想使用数学,那么另一种纯R的方法是:
result = rep(1,length(x1))
result[x1<X2] = -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.