首页 > 解决方案 > 布尔结果显示 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))

标签: rboolean

解决方案


'b'是 中的对象的名称list1%in%匹配值向量中的值。

如果您要创建list1一个包含 value 的列表'b',那么您的条件将是TRUE。看:

list1 <- list('b')
> 'b' %in% test1
[1] TRUE

在您的情况下,您可以匹配'b'vector names(list1)。因此'b' %in% names(list1),在您的- 条件下使用if以使其工作。


推荐阅读