在R中,可以访问列表元素$.当一个人访问一个未包含在列表中的字段时,结果值就是NULL.这在我的代码中我进一步使用对象的部分是有问题的.拿这个代码:
l <- list(foo = 1, bar = 2)
print(l$foobar)
Run Code Online (Sandbox Code Playgroud)
输出只是NULL没有错误,也没有警告.我知道可能需要这样做,以便新元素(l$foobar <- 3)的分配可以工作.
有什么方法可以使列表中的字段的读取访问成为硬错误(如果它不存在)?
您可以尝试编写自己的函数:
extract_ls <- function(ls, el){
if (!el %in% names(ls)) stop(paste0("The specified element ", el, " does not exist in the list"))
else return(ls[[el]])
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
extract_ls(l, "baz")
#Error in extract_ls(l, "baz") :
# The specified element baz does not exist in the list
extract_ls(l, "bar")
#[1] 2
Run Code Online (Sandbox Code Playgroud)
请注意,我使用[[而不是$. 这两者执行相同的操作,但$进行部分匹配。还[[需要一个字符串。
要使其成为中缀函数,只需将函数名称更改为`%[[%`。那么用法就是:
l %[[% "baz"
#Error in l %[[% "baz" :
# The specified element baz does not exist in the list
l %[[% "bar"
#[1] 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |