如果存在[list1$b],为什么布尔值是FALSE?参见下面代码中的步骤-4。由于值FALSE,if语句将不会被执行。
其他观察:我还注意到,在整个脚本的第二次运行中,脚本声明'a在list1中缺失‘,添加a,即使列表1$a确实存在。
需要行为/结果:(如果[list1$b]存在),将布尔值设置为TRUE并运行if statement。另外,在第二轮总脚本中,list1 1$a应该检测到list1 1$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))发布于 2018-07-16 09:03:21
'b'是list1中对象的名称。%in%匹配值向量中的值。
如果要将list1创建为包含值'b'的列表,则条件为TRUE。请参见:
list1 <- list('b')
> 'b' %in% test1
[1] TRUE在您的情况下,可以将'b'与向量names(list1)匹配。因此,使用'b' %in% names(list1)在您的if-condition中使其工作。
https://stackoverflow.com/questions/51358011
复制相似问题