假设我有一个如下列表
foo=list(bar="hello world")
Run Code Online (Sandbox Code Playgroud)
我想检查一下我的列表是否有特定的密钥.我会观察foo$bar2将返回NULL任何bar2不相等的bar,所以我想我可以检查返回值是否为null,但这似乎不起作用:
if (foo$bar2==NULL) 1 # do something here
Run Code Online (Sandbox Code Playgroud)
但是,这会给出错误:
Error in if (foo$bar2 == NULL) 1 : argument is of length zero
Run Code Online (Sandbox Code Playgroud)
然后我尝试NULL是否等于false,就像在C中一样:
if (foo$bar2) 1 # do something here
Run Code Online (Sandbox Code Playgroud)
这给出了同样的错误.
我现在有两个问题.如何检查列表是否包含密钥?我如何检查表达式是否为空?
42-*_*42- 28
"键"的概念在R中称为"名称".
if ("bar" %in% names(foo) ) { print("it's there") } # ....
Run Code Online (Sandbox Code Playgroud)
它们存储在一个.Names使用以下names函数命名和提取的特殊属性中:
dput(foo)
#structure(list(bar = "hello world"), .Names = "bar")
Run Code Online (Sandbox Code Playgroud)
我在这里提出了一个语义上的谨慎,因为这个词的两个不同用法导致混淆的常见原因:R中的"名称":有.Names属性,但nameR 中的单词有一个完全不同的用途,使用具有独立于任何检查或提取功能的值的字符串或标记,例如$或[.任何以字母或句号开头并且其中包含其他特殊字符的标记都可以是有效的name.可以使用exists给定引用版本的函数来测试它name:
exists("foo") # TRUE
exists(foo$bar) # [1] FALSE
exists("foo$bar")# [1] FALSE
Run Code Online (Sandbox Code Playgroud)
所以这个词name在R中有两个不同的含义,你需要意识到这种歧义,以了解语言的部署方式.的.Names含义是指具有特殊用途的属性,同时names,意思是指所谓的"语言的对象".这个词symbol是这个词的第二个含义的同义词.
is.name( quote(foo) ) #[1] TRUE
Run Code Online (Sandbox Code Playgroud)
然后展示你关于测试无效的第二个问题可能会如何:
if( !is.null(foo$bar) ) { print("it's there") } # any TRUE value will be a 1
Run Code Online (Sandbox Code Playgroud)