r - 布尔结果显示 FALSE,应返回 TRUE
问题描述
如果[list1$b]
存在,布尔值怎么来的FALSE
?请参阅下面代码中的步骤 4。由于 value FALSE
, if 语句将不会被执行。
其他观察:我还注意到,在整个脚本的第二次运行期间,脚本指出 'a 在 list1 中丢失。添加 a',即使 [list1$a] 确实存在。
想要的行为/结果:如果[list1$b]
存在,则将布尔值设置为TRUE
并运行if statement
. 此外,在第二轮总脚本中,[list1$a] 应该检测到 [list1$a] 存在。
##########
# Step-1 #
##########
# Create list [list1] if missing.
if (!exists('list1')) {
list1 <- list()
}
##########
# Step-2 #
##########
# Add variable [b] in list [list1].
list1$b <- 1
##########
# Step-3 #
##########
# Create variable [a] in list [list1] if missing.
if (!'a' %in% list1) {
print ('a is missing in list1. Adding a')
list1$a <- 2
}
##########
# Step-4 #
##########
# Execute only print, if variable [b] in list [list1] exists.
# Note! Even though variable [b] in list [list1] exists, the boolean result is FALSE.
if ('b' %in% list1) {
print ('b exists in list1. Do nothing')
}
# Print-out boolean result of Step-4:
boolean.result.of.step.four <- ('b' %in% list1)
print (paste0('Boolean result of step-4: ', boolean.result.of.step.four))
解决方案
'b'
是 中的对象的名称list1
。%in%
匹配值向量中的值。
如果您要创建list1
一个包含 value 的列表'b'
,那么您的条件将是TRUE
。看:
list1 <- list('b')
> 'b' %in% test1
[1] TRUE
在您的情况下,您可以匹配'b'
vector names(list1)
。因此'b' %in% names(list1)
,在您的- 条件下使用if
以使其工作。
推荐阅读
- c++ - 所有平均值的c ++ struct平均值
- reactjs - 使用带有 reactfire 的 firestore 模拟器
- r - 为一行是否包含任何列中的字符串创建一个逻辑列
- php - 父项下的下拉菜单中的子菜单?
- python - pyTelegramBotAPI 消息缓存 threading.lock
- node.js - 在后端使用 express 响应路由
- html - 将转义应用于 DT 表时 HTML 表未呈现为 FALSE
- vim - 当我用 sudo 打开它时,gvim 颜色方案看起来不同
- html - 单击时复选框不起作用,我该如何解决?
- c# - C# 应用程序在 OCR 完成后不读取 txt 文件,无论内容如何