Reputation: 606
I am trying to create a nested list where the value from one vector becomes the name and the process repeats until the last vector which stores an actual value. I was thinking that the code I have below would work, but it isn't
chips[[toString(aCor[i])]]=list(toString(bCor[i])=list(toString(cCor[i])=list(toString(dCor[i])=eCor[i])))
I was expecting something like this if 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)
Resulting list
["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
Sorry if the expected list is formatted poorly. I wasnt sure the best way to do it. If there is a better way of doing this than a list I am open to suggestions, I would have used a dictionary in python and this was the closest I could find that would replicate it. I am currently getting this error
Error in parse(text = script) : parse error in text argument: unexpected '=' in function argument before
Upvotes: 1
Views: 238
Reputation: 606
This is the code I ended up making with the help of akrun in this question and another code that I found on this page written by IRTFM.
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
Output:
$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
Upvotes: 1
Reputation: 887951
We could use lst
from purrr
or dplyr
(or need setNames
) which would work with assignment (:=
)
nm1 <- 'a'
nm2 <- 'b'
dplyr::lst(!! nm1 := lst(!! nm2 := 5))
#$a
#$a$b
#[1] 5
If we need to create a nested list
, use a for
loop
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]]
}
-output
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)
Upvotes: 2