通过将位置表示为整数向量来更新嵌套列表中的值。

huangapple go评论85阅读模式
英文:

Updating a value in a nested list by having the position as an integer vector

问题

让我们考虑我有一个嵌套列表

  1. x = list(a1 = list(b1 = list(c1 = 1), b2 = list(d1 = 1, d2 = 2, d3 = 3)))

此外,我有一个索引,给出了嵌套列表中的位置,以及我想要更新的值

  1. index = c(1,1,1) # 应该更新c1
  2. value = 100

手动操作如下

  1. x[[1]][[1]][1] = value
  2. x

我也知道可以这样写

  1. index = c(1,2,2) # 应该更新d2
  2. `[[`(`[[`(`[[`(x, 1), 2), 2) = value
  3. x

问题:有没有一种编程方式来设置嵌套列表的索引处的值?

要仅读取该值,可以按以下方式进行 - 但这不允许我更改它。

  1. ifuns <- lapply(index, function(i) {function(x) `[[`(x, i)})
  2. Funcall <- function(f, ...) f(...)
  3. Reduce(Funcall, rev(ifuns), x, right = TRUE)

这明显失败了

  1. Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value
  1. Error in Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value :
  2. could not find function "Reduce<-"
英文:

Let's consider I have a nested list

  1. x = list(a1 = list(b1 = list(c1 = 1), b2 = list(d1 = 1, d2 = 2, d3 = 3)))

Further I have an index, giving me the position in the nested list, and a value that I want to update

  1. index = c(1,1,1) # should update c1
  2. value = 100

Manually I can do is as follows

  1. x[[1]][[1]][1] = value
  2. x

I also know I can write it as such

  1. index = c(1,2,2) # should update d2
  2. `[[`(`[[`(`[[`(x, 1), 2), 2) = value
  3. x

Question: Is there a programmatic way to set the value at index for the nested list?

To only read the value I could go the following way - but it does not allow me to change it.

  1. ifuns <- lapply(index, function(i) {function(x) `[[`(x, i)})
  2. Funcall <- function(f, ...) f(...)
  3. Reduce(Funcall, rev(ifuns), x, right = TRUE)

This (obviously) fails

  1. Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value
  1. Error in Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value :
  2. could not find function "Reduce<-"

答案1

得分: 2

你是在寻找这个吗?

  1. x[[index]] <- value
  2. # > x
  3. # $a1
  4. # $a1$b1
  5. # $a1$b1$c1
  6. # [1] 100
  7. #
  8. #
  9. # $a1$b2
  10. # $a1$b2$d1
  11. # [1] 1
  12. #
  13. # $a1$b2$d2
  14. # [1] 2
  15. #
  16. # $a1$b2$d3
  17. # [1] 3
英文:

Are you looking for this?

  1. x[[index]] &lt;- value
  2. # &gt; x
  3. # $a1
  4. # $a1$b1
  5. # $a1$b1$c1
  6. # [1] 100
  7. #
  8. #
  9. # $a1$b2
  10. # $a1$b2$d1
  11. # [1] 1
  12. #
  13. # $a1$b2$d2
  14. # [1] 2
  15. #
  16. # $a1$b2$d3
  17. # [1] 3

huangapple
  • 本文由 发表于 2023年2月16日 19:10:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定