【发布时间】:2011-12-04 21:44:47
【问题描述】:
问题
我想测试一个列表的元素是否存在,这里是一个例子
foo <- list(a=1)
exists('foo')
TRUE #foo does exist
exists('foo$a')
FALSE #suggests that foo$a does not exist
foo$a
[1] 1 #but it does exist
在这个例子中,我知道foo$a 存在,但测试返回FALSE。
查看?exists,发现with(foo, exists('a')返回TRUE,但不明白为什么exists('foo$a')返回FALSE。
问题
- 为什么
exists('foo$a')返回FALSE? - 使用
with(...)是首选方法吗?
【问题讨论】:
-
也许是
!is.null(foo$a)(或!is.null(foo[["a"]])为了安全起见)? (或exists("a",where=foo)) -
@BenBolker 谢谢 - 会是一个很好的答案;为什么首选后者?
-
@David 部分匹配...试试上面的
foo <- list(a1=1)
标签: r