在 R 中,如何构建一个列表,其中一些元素引用列表中较早的元素?

In R, how can I build a list with some elements referring to earlier elements in the list?

我正在尝试做这样的事情:

opts = list(
  width=128,
  overlap=width/2,
)

但是,正如预期的那样,我得到了

Error: object 'width' not found

挽救这段代码片段的好习惯用法是什么?

您可以使用 dplyr::lstlist 相同,但在这里您可以按顺序构建组件。

dplyr::lst(
  width = 128, 
  overlap=width/2,
)

#$width
#[1] 128

#$overlap
#[1] 64

使用 base R,最好的办法是先用宽度元素定义列表,然后在以后的赋值中重用它:

lst <- list(width=128)
lst$height <- lst$width / 2
lst

$width
[1] 128

$height
[1] 64

另一种选择是:

opts = list(
  width={width<-128},
  overlap=width/2
)