我有一个多级列表 l
具有任意数量的级别和条目。举一个简单的例子:
l <- list(a = 1,
b = list(x = 2, y = 3),
c = list(dog = 5, cat = list(fish = 3, mouse = 10))
)
在我的软件包中,用户通过一个“地址”,该“地址”指定了此列表中的对象。地址作为字符串传递:
address = "$c$cat$fish"
这不包括列表本身的名称。
我编写了一个函数,该功能检查地址是否为“有效”,从某种意义上说我想检查指定地址是否存在对象。该函数的主要实质如下:
# this is the call to evaluate, as a string
expr_str <- paste0("address_value <- l", address)
# evaluate the call
eval(str2lang(expr_str))
if(is.null(address_value)){
warning("Address is NULL or not found in list")
}
现在,这起作用(尽管可能有一种更优雅的方法可以做到这一点)。但是问题在于我在CMD检查中获得了注释,因为 address_value
没有可见的绑定,因为它是在 eval()
中创建的。
我想摆脱注释,但我不确定如何在不使用 eval()
的情况下检索 address
上的任何内容(或不是)。
谁能帮助解决这个问题?
I have a multi-level list l
with an arbitrary number of levels and entries. To give a simple example:
l <- list(a = 1,
b = list(x = 2, y = 3),
c = list(dog = 5, cat = list(fish = 3, mouse = 10))
)
In my package, the user passes an "address" which specifies an object in this list. The address is passed as a string, of the form:
address = "$c$cat$fish"
This excludes the name of the list itself.
I have written a function which checks whether the address is "valid", in the sense that I want to check whether an object exists at the specified address. The main substance of the function is as follows:
# this is the call to evaluate, as a string
expr_str <- paste0("address_value <- l", address)
# evaluate the call
eval(str2lang(expr_str))
if(is.null(address_value)){
warning("Address is NULL or not found in list")
}
Now, this works (although there is probably a more elegant way to do it). But the problem is that I get a NOTE in the CMD check because the address_value
doesn't have a visible binding, because it is created inside eval()
.
I want to get rid of the note but I'm not sure how to retrieve whatever is (or isn't) at address
without using eval()
.
Can anyone help with this problem?
发布评论
评论(2)
您是否考虑过使用
purrr :: Pluck
?我认为这与您的要求相符:Have you considered using
purrr::pluck
? I think it matches your requirements:eval> eval
的 的分配,该可以避免CMD检查中未宣布的变量NAG。这导致:
The assignment to
address_value
can be outside of theeval
, which avoids the undeclared variable nag in the CMD check.Which results in: