Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何在嵌套列表的叶上轻松迭代_R - Fatal编程技术网

R 如何在嵌套列表的叶上轻松迭代

R 如何在嵌套列表的叶上轻松迭代,r,R,假设我有一个清单: a <- list(a = 1, b = list(a = list(b = 1, c = 2), c = 1), c = 1) a这个怎么样 a <- list(a = 1, b = list(a = list(b = 1, c = 2), c = 1), c = 1) aunls <- unlist(a) aunls[!grepl('c', names(aunls))] a这个怎么样 a <- list(a = 1, b = list(a =

假设我有一个清单:

a <- list(a = 1, b = list(a = list(b = 1, c = 2), c = 1), c = 1)
a这个怎么样

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

aunls <- unlist(a)
aunls[!grepl('c', names(aunls))]
a这个怎么样

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

aunls <- unlist(a)
aunls[!grepl('c', names(aunls))]

a您可以使用递归lappy函数来执行此操作,例如:

foo <- function(x, name) {
  if(any(idx <- names(x) == name)) x <- x[!idx]
  if(is.list(x)) lapply(x, foo, name) else x
}

foo(a, "c")
# $a
# [1] 1
# 
# $b
# $b$a
# $b$a$b
# [1] 1

foo您可以使用递归lappy函数来实现这一点,例如:

foo <- function(x, name) {
  if(any(idx <- names(x) == name)) x <- x[!idx]
  if(is.list(x)) lapply(x, foo, name) else x
}

foo(a, "c")
# $a
# [1] 1
# 
# $b
# $b$a
# $b$a$b
# [1] 1
foo