英文:
Comparing if one value fits between other 2
问题
我有3个值要比较,分别是a、b和c。我需要创建一个循环,如果b落在a和c之间,就返回1。然而,它们不是线性的值。a可能比c小,反之亦然。
我应该如何创建一个if else循环,如果a≤b≤c或c≤b≤a时返回1,如果不在这些范围内则返回0。
英文:
I have 3 values to compare a, b, c. I need to form a loop that returns 1 if b falls between a and c. However they are not linear values. a could be smaller than c and vice versa.
How do I make a if else loop that returns 1 if a<=b<=c Or c<=b<=a and 0 if it falls outside of those bounds.
答案1
得分: 0
你可以对每个条件使用 ifelse()
:
ifelse(a <= b & b <= c, 1, 0) + ifelse(a >= b & b >= c, 1, 0)
如果 a、b 和 c 都是长度为 n 的向量,这将返回一个长度为 n 的由零和一组成的向量。
如果 a=b=c,使得两个测试都为真,你会得到一个两。为了避免这种情况,你可以将整个表达式包装在 pmin(.,1)
中,其中点表示上述表达式,或者将两个条件都放在 ifelse()
语句中,如下所示:
ifelse(a <= b & b <= c | a >= b & b >= c, 1, 0)
英文:
You can use ifelse()
for each criteria:
ifelse(a<=b & b<=c, 1, 0) + ifelse(a>=b & b>=c, 1, 0)
If a, b, and c are vectors of length n, this will return a length-n vector of zeros and ones.
If a=b=c such that both tests are true, you would get a two. To avoid this, you can wrap the whole expression in pmin(.,1)
where the dot indicates the above expression, or put both criteria in the ifelse()
statement like so:
ifelse( a<=b & b<=c | a>=b & b>=c, 1, 0)
答案2
得分: 0
One way using ifelse
, although the recommendation is to avoid using reserved names in R
as we are using c
here which is a reserved name:
fun_fall <- function(a, b, c) ifelse((a <= b & b <= c) | (c <= b & b <= a), 1, 0)
#example
fun_fall(3, 1, 3)
0
fun_fall(1, 2, 3)
1
英文:
One way using ifelse
, although the recommendation is to avoid using reserved names in R
as we are using c
here which is a reserved name:
fun_fall <- \(a,b,c) ifelse((a <= b & b <= c) | (c <= b & b <= a), 1, 0)
#example
fun_fall(3,1,3)
0
fun_fall(1,2,3)
1
答案3
得分: 0
如何考虑在代码中引入%between%
函数,来提高代码的可读性和编写的便捷性?
library(data.table)
a <- 1
b <- 2
c <- 3
b %between% sort(c(a, c)) # TRUE
a <- 3
c <- 1
b %between% sort(c(a, c)) # TRUE
英文:
How about introducing %between%
from data.table for extra readability and ease of coding?
library(data.table)
a <- 1
b <- 2
c <- 3
b %between% sort(c(a,c)) # TRUE
a <- 3
c <- 1
b %between% sort(c(a,c)) # TRUE
答案4
得分: 0
var check = false;
if (b >= a) {
if (b <= c) {
check = true;
}
}
if (b <= a) {
if (b >= c) {
check = true;
}
}
英文:
var check = false;
if(b>=a)
{
if (b<=c)
{
check = true;
}
}
if (b<=a)
{
if(b>=c)
{
check = true;
}
}
not sure about syntax to specified language but that pretty much how you do it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论