【问题标题】:R creating a nested list from multiple vectorsR从多个向量创建一个嵌套列表
【发布时间】:2020-11-26 09:20:58
【问题描述】:

我正在尝试创建一个嵌套列表,其中一个向量的值成为名称,并且该过程重复,直到最后一个存储实际值的向量。我在想我下面的代码可以工作,但事实并非如此

chips[[toString(aCor[i])]]=list(toString(bCor[i])=list(toString(cCor[i])=list(toString(dCor[i])=eCor[i])))

如果aCor=c(1,2,2,1), bCor=c(4,5,6,4), cCor=c(3,3,2,3), dCor=c(1,4,5,1), eCor=c(1,3,4,7),我期待这样的事情

结果列表 ["1"=["4"=["3"=["1"= 7]]], "2"=["5"=["3"=["4"=3]],"6"=["2"=["5"=4]]]]

$1
$1$4
$1$4$3
$1$4$3$1
[1] 7

$2
$2$5
$2$5$3
$1$4$3$4
[1] 3

$2
$2$6
$2$6$2
$1$6$2$5
[1] 4

很抱歉,如果预期的列表格式不正确。我不确定最好的方法。 如果有比我愿意接受建议的列表更好的方法来做到这一点,我会在 python 中使用字典,这是我能找到的最接近的可以复制它的字典。 我目前收到此错误

Error in parse(text = script) : parse error in text argument: unexpected '=' in function argument before

【问题讨论】:

  • 请用dput展示一个可重复的小例子
  • @akrun 我目前收到此错误,所以我无法给出可重现的示例 解析中的错误(文本 = 脚本):文本参数中的解析错误:之前的函数参数中出现意外的“=”
  • 这只是为了了解您的输入和期望是什么
  • @akrun 我有。这是结束前的2段

标签: r nested-lists


【解决方案1】:

我们可以使用来自purrrdplyrlst(或需要setNames),这将与分配(:=)一起使用

nm1 <- 'a'
nm2 <- 'b'
dplyr::lst(!! nm1 := lst(!! nm2 := 5))
#$a
#$a$b
#[1] 5

如果我们需要创建嵌套的list,请使用for 循环

lst1 <- list()

for(i in seq_along(aCor)) {
      an <- as.character(aCor[i])
      
      bn <- as.character(bCor[i])
      cn <- as.character(cCor[i])
      dn <- as.character(dCor[i])
      lst1[[an]][[bn]][[cn]][[dn]] <- eCor[[i]]
      

}

-输出

lst1
#$`1`
#$`1`$`4`
#$`1`$`4`$`3`
#$`1`$`4`$`3`$`1`
#[1] 7




#$`2`
#$`2`$`5`
#$`2`$`5`$`3`
#$`2`$`5`$`3`$`4`
#[1] 3



#$`2`$`6`
#$`2`$`6`$`2`
#$`2`$`6`$`2`$`5`
#[1] 4

数据

aCor <- c(1,2,2,1)
bCor <- c(4,5,6,4)
cCor <- c(3,3,2,3)
dCor <- c(1,4,5,1)
eCor <- c(1,3,4,7)

【讨论】:

  • 你为什么使用 := 而不是 = 以及为什么 !!
  • @NikitaBelooussov = 不会评估它会给list(nm1 = 5) 的对象
  • 还有!!做什么?
  • 它评估对象
  • 感谢您的帮助。我不确定您的代码为什么不起作用,我提出的代码似乎在我的情况下会起作用
【解决方案2】:

这是我在 akrun 的帮助下最终在这个问题中编写的代码,以及我在 IRTFM 编写的 page 上找到的另一个代码。

require(dplyr)

aCor <- c(1,2,2,1)
bCor <- c(4,5,6,4)
cCor <- c(3,3,2,3) 
dCor <- c(1,4,5,1)
eCor <- c(1,3,4,7)

appendList <- function (x, val) 
{
   stopifnot(is.list(x), is.list(val))
   xnames <- names(x)
   for (v in names(val)) {
      x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
        appendList(x[[v]], val[[v]])
        else c(val[[v]])
    }
   x
}


chips <- list()

for(i in seq_along(aCor)) {
   an <- as.character(aCor[i]) 
   bn <- as.character(bCor[i])
   cn <- as.character(cCor[i])
   dn <- as.character(dCor[i])
   #chips[[an]]=lst(!! bn := lst(!! cn := lst(!! dn := eCor[i])))
   list1=lst(!! an := lst(!! bn := lst(!! cn  := lst(!! dn:= eCor[i]))))
   chips=appendList(chips,list1)
}

chips

输出:

$1
$1$4
$1$4$3
$1$4$3$1
[1] 7

$`2`
$`2`$`5`
$`2`$`5`$`3`
$`2`$`5`$`3`$`4`
[1] 3

$`2`$`6`
$`2`$`6`$`2`
$`2`$`6`$`2`$`5`
[1] 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多