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

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

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

问题

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

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

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

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

手动操作如下

x[[1]][[1]][1] = value
x

我也知道可以这样写

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

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

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

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

这明显失败了

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

Let's consider I have a nested list

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

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

Manually I can do is as follows

x[[1]][[1]][1] = value
x

I also know I can write it as such

index = c(1,2,2) # should update d2
`[[`(`[[`(`[[`(x, 1), 2), 2) = value
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.

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

This (obviously) fails

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

答案1

得分: 2

你是在寻找这个吗?

x[[index]] <- value
    
# > x
# $a1
# $a1$b1
# $a1$b1$c1
# [1] 100
# 
# 
# $a1$b2
# $a1$b2$d1
# [1] 1
# 
# $a1$b2$d2
# [1] 2
# 
# $a1$b2$d3
# [1] 3
英文:

Are you looking for this?

x[[index]] &lt;- value

# &gt; x
# $a1
# $a1$b1
# $a1$b1$c1
# [1] 100
# 
# 
# $a1$b2
# $a1$b2$d1
# [1] 1
# 
# $a1$b2$d2
# [1] 2
# 
# $a1$b2$d3
# [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:

确定