[英]Changing list names dynamically in R using non-standard evaluation
我尝试做的是在 R 中动态设置列表元素的名称,从预定义的字符串并使用非标准评估。
请参阅下面的示例:
library(rlang)
dynamic.listname <- "important.name"
# this works (as was also demonstrated in the answer to this related question: https://stackoverflow.com/questions/35034384/dynamically-creating-named-list-in-r ):
list.to.display <- list(1,2,3)
names(list.to.display) <- c("first.fixed.name", dynamic.list.name, "second.fixed.name")
# But I would like something like this to work
list.to.display <- list(
"first.fixed.name" = 1,
!!dynamic.listname := 2,
"second.fixed.name" = 3
)
# it gives the following error:
# Error: `:=` can only be used within a quasiquoted argument
我基于 tidyverse 示例编写了上面的代码,该网站上名为“设置变量名称”的最后一段: https ://dplyr.tidyverse.org/articles/programming.html
因此,'dynamic.listname' 应该首先作为存储在该变量中的字符串进行评估。 然后,该字符串应作为列表中的名称之一实现。 有谁知道在这种情况下如何实施非标准评估? Base R 也适合我。 我想要当前尚未工作的其他选项的原因是我想使用的列表嵌入在特定的包函数中,因此从外部操作有点困难。 此外,我正在尝试更多地了解非标准评估。
在基础 R 中,您可以使用deparse(substitute(x))
:
make_list <- function(named_var, value)
{
result <- list(deparse(substitute(value)))
names(result) <- deparse(substitute(named_var))
result
}
make_list(hello, world)
#> $hello
#> [1] "world"
由reprex 包(v0.3.0) 于 2020 年 2 月 24 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.