代码之家  ›  专栏  ›  技术社区  ›  Toolbox

布尔结果显示为假,应返回真

  •  0
  • Toolbox  · 技术社区  · 6 年前

    如果 [list1$b] 存在,为什么布尔值是 FALSE ?参见下面代码中的步骤4。由于价值 错误的 ,将不执行if语句。

    其他观察: 我还注意到,在整个脚本的第二次运行期间,脚本声明“a在列表1中丢失”。添加',即使[list1$a]确实存在。

    想要的行为/结果: 如果 [列表1$B] exists将布尔值设置为 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))
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   LAP    6 年前

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

    如果你能创造 表1 作为包含值的列表 “B” 你的情况是 TRUE . 见:

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

    在你的情况下,你可以匹配 “B” 用矢量 names(list1) . 因此使用 'b' %in% names(list1) 在你的 if -使其工作的条件。