r - if else 语句连接 - R
问题描述
这是一个非常常见的问题:1、2、3、4、5,但我什至找不到我的问题的答案。
If a == 1, then do X.
If a == 0, then do Y.
If a == 0 and b == 1, then do Z.
只是为了解释一下:if else 语句必须执行Y
ifa==0
无论b
. 但是 ifb == 1
和a == 0
,Z
将对已经由Y
.
我当前的代码及其错误:
if (a == 1){
X
} else if(a == 0){
Y
} else if (a == 0 & b == 1){
Z}
Error in !criterion : invalid argument type
解决方案
else
仅当先前if
未发生时才会发生。
当你说
但是 if
b == 1
和a == 0
,Z
将对已经完成的那些做额外的改变Y
然后你有两个选择:
## Option 1: nest Z inside Y
if (a == 1){
X
} else if(a == 0){
Y
if (b == 1){
Z
}
}
## Option 2: just use `if` again (not `else if`):
if (a == 1) {
X
} else if(a == 0) {
Y
}
if (a == 0 & b == 1) {
Z
}
真的,你根本不需要任何else
东西。
## This will work just as well
## (assuming that `X` can't change the value of a from 1 to 0
if (a == 1) {
X
}
if (a == 0) {
Y
if (b == 1){
Z
}
}
通常else
,当您想要一个“最终”操作时需要,该操作仅在没有使用之前的if
选项时才完成,例如:
# try to guess my number between 1 and 10
if (your_guess == 8) {
print("Congratulations, you guessed my number!")
} else if (your_guess == 7 | your_guess = 9) {
print("Close, but not quite")
} else {
print("Wrong. Not even close!")
}
在上面,else
它很有用,因为我不想列举用户可能输入的所有其他可能的猜测(甚至是错误的输入)。如果他们猜到 8,他们就赢了。如果他们猜 7 或 9,我告诉他们他们很接近。其他的,不管是什么,我只是说“错”。
注意:这对于一般的编程语言都是正确的。它不是 R 独有的。
但是,由于这是在 R 标签中,我应该提到 R 有if{}else{}
and ifelse()
,它们是不同的。
if{}
(并且可选else{}
)评估单个条件,您可以运行代码来根据该条件执行任何操作。{}
ifelse()
是一个矢量化函数,它的参数是test
,yes
,no
. 计算test
结果为 TRUE 和 FALSE 值的布尔向量。yes
和no
参数必须是与 长度相同的test
向量。结果将是一个长度与 相同的向量,test
对应的值为yes
(whentest
is TRUE) 和no
(whentest
is FALSE)。
推荐阅读
- docker - 没有这样的文件或目录 package.json
- javascript - 在 DYGRAPH 中,我想在画布上(在柱形图中)永久显示所有数据点,在列的顶部?谢谢
- c# - 如何从对象列表中获取对象,这些对象列表中包含对象中另一个列表中的重复属性?
- ssis - SSIS 从 ODBC 查询结果中设置变量值
- virtual-machine - 如何提取 qcow2 虚拟磁盘映像?
- c - 在变量定义期间,自赋值有什么作用吗?
- reactjs - 在让视频录制组件在我的 React 应用程序中工作时需要帮助
- r - 使用棒球的日期返回错误
- content-security-policy - CSP 标头指令问题
- r - 将两个命名向量/矩阵相乘,应用 n-gram 模型 (stringdist::qgrams)