简体   繁体   English

R:同一列表中的引用列表项

[英]R: Reference list item within the same list

In R, we can reference items created within that same list, ie:在 R 中,我们可以引用在同一个列表中创建的项目,即:

list(a = a <- 1, b = a)

I am curious if there is a way to write a function which takes the place of a = a <- 1 .我很好奇是否有办法编写一个函数来代替a = a <- 1 That is, if something like也就是说,如果像

`%=%` <- function(x,y) {
  envir <- environment()
  char_x <- deparse(substitute(x))
  assign(char_x, y, parent.env(envir))
  unlist(lapply(setNames(seq_along(x),char_x), function(T) y))
}
# does not work
list(a%=%1, b=a)

is possible in R (ie returns the list given above)?在 R 中是可能的(即返回上面给出的列表)?

edit: I think this boils down to asking, 'can we call list with a language object that preserves all aspects of manually coding list?'编辑:我认为这归结为问,“我们可以使用保留手动编码列表所有方面的语言对象调用列表吗?” (specifically, assigns the list's names attribute the left-hand side of the language element). (具体来说,将列表的名称属性分配给语言元素的左侧)。

It seems to me that below shows that such a solution is hopeless.在我看来,下面表明这样的解决方案是无望的。

my_call <- do.call(substitute, list(expr(expr = {x = y}), list(x=quote(a), y=1)))
equals <- languageEl(my_call, which = 1)
str(equals)
do.call(list, list(equals))

Welp, the clever folk behind tibble have figured this out in their lst() function (also in package dplyr )韦尔普,背后的聪明人tibble他们已经想通了这一点lst()函数(也包dplyr

library(dplyr)
lst(a=1, b=a, c=c(3,4), d=c)

What a useful feature!多么有用的功能!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM