R 附加到任意嵌套的列表

R 附加到任意嵌套的列表,r,R,我使用嵌套的列表结构作为类的基础。每个类对象可以包含另一个类对象的实例,该类对象将用于链接一系列命令。我试图重载+操作符,以便能够迭代地构建命令集合。这需要找到“最深”的命令并附加到它。这就是我不走运的地方 # an aribitrarily nested list tmp <- list(x = list(x = list(x = list()))) # find deepest 'x' last.x <- function(e) { while(!is.null(e$x))

我使用嵌套的列表结构作为类的基础。每个类对象可以包含另一个类对象的实例,该类对象将用于链接一系列命令。我试图重载
+
操作符,以便能够迭代地构建命令集合。这需要找到“最深”的命令并附加到它。这就是我不走运的地方

# an aribitrarily nested list
tmp <- list(x = list(x = list(x = list())))

# find deepest 'x'
last.x <- function(e) {
  while(!is.null(e$x)){
    e <- e$x
  }
  return(e)
}

# I need to be able to append to the deepest 'x' in the list. Ideally:
last.x(tmp)$x <- list()
#一个任意嵌套的列表

tmp如果从R中的数据结构中提取一些值,然后更改提取的对象,这不会影响原始数据结构(即提取的对象不会像指向原始数据的指针一样)。例如,考虑从虹膜数据集复制物种,然后改变提取的值:

species <- iris$Species
species[1] <- "virginica"
species[1]
# [1] virginica
# Levels: setosa versicolor virginica
iris$Species[1]
# [1] setosa
# Levels: setosa versicolor virginica

species提供我的解决方案,希望对其他人有用。感谢您提供的灵感。在尝试创建一个简单的示例时,我排除了一些使直接应用答案变得困难的细节

从三个对象开始,每个对象都有一个深度为1的列表:

obj1 <- structure(list(), class='obj')
obj2 <- structure(list(), class='obj')
obj3 <- structure(list(), class='obj')
obj1
tmp
# $x
# $x$x
# $x$x$x
# list()

rec <- function(x) {
  if (is.null(x$x))  return(list(x=list()))
  else  return(list(x=rec(x$x)))
}
rec(tmp)
# $x
# $x$x
# $x$x$x
# $x$x$x$x
# list()
obj1 <- structure(list(), class='obj')
obj2 <- structure(list(), class='obj')
obj3 <- structure(list(), class='obj')
`+.obj` <- function(e1, e2) {  
  if (is.null(e1$x)) {
    e1$x <- e2
  } else {
    e1$x <- e1$x + e2
  }
  return(e1)  
}
res <- obj1 + obj2 + obj3

> str(res)
List of 1
 $ x:List of 1
  ..$ x: list()
  .. ..- attr(*, "class")= chr "obj"
  ..- attr(*, "class")= chr "obj"
 - attr(*, "class")= chr "obj"