Home > database >  Rename triple nested lists in r
Rename triple nested lists in r

Time:11-17

How do I change the names of the triple nested lists across all nested lists?

Here is a triple nested list:

list.A <- list(a = c(1,2,5,6), b = c(2,4,6,5), c = c(2,4,2,5))
list.B <- list(a = c(7,7,7,7), b = c(8,8,8,8), c = c(9,9,9,9))
weights <- list(list.A, list.B)
names(weights) <- c("list.A", "list.B")

list.A <- list(a = c(2,2,2,2), b = c(3,3,3,3), c = c(4,4,4,4))
list.B <- list(a = c(5,5,5,5), b = c(6,6,6,6), c = c(7,7,7,7))
scores <- list(list.A, list.B)
names(scores) <- c("list.A", "list.B")

megalist <- list(weights, scores)
names(megalist) <- c("weights", "scores")
megalist

> megalist
$weights
$weights$list.A
$weights$list.A$a
[1] 1 2 5 6

$weights$list.A$b
[1] 2 4 6 5

$weights$list.A$c
[1] 2 4 2 5


$weights$list.B
$weights$list.B$a
[1] 7 7 7 7

$weights$list.B$b
[1] 8 8 8 8

$weights$list.B$c
[1] 9 9 9 9



$scores
$scores$list.A
$scores$list.A$a
[1] 2 2 2 2

$scores$list.A$b
[1] 3 3 3 3

$scores$list.A$c
[1] 4 4 4 4


$scores$list.B
$scores$list.B$a
[1] 5 5 5 5

$scores$list.B$b
[1] 6 6 6 6

$scores$list.B$c
[1] 7 7 7 7

I would like to change the names of the 3 lists IN list.A, which is in both weights and scores.

To make things more complicated, I would like to change the names of the 3 lists in list.A to the rownames of mydf.

Here is mydf:

mydf <- as.data.frame(c(12, 34, 72))
rownames(mydf) <- c("Apple", "Orange", "Banana")
colnames(mydf) <- "variable"

> mydf
    
variable
<dbl>
            
Apple   12          
Orange  34          
Banana  72

The result should look like this:

> desired.output
$weights
$weights$list.A
$weights$list.A$Apple
[1] 1 2 5 6

$weights$list.A$Orange
[1] 2 4 6 5

$weights$list.A$Banana
[1] 2 4 2 5


$weights$list.B
$weights$list.B$a
[1] 7 7 7 7

$weights$list.B$b
[1] 8 8 8 8

$weights$list.B$c
[1] 9 9 9 9



$scores
$scores$list.A
$scores$list.A$Apple
[1] 2 2 2 2

$scores$list.A$Orange
[1] 3 3 3 3

$scores$list.A$Banana
[1] 4 4 4 4


$scores$list.B
$scores$list.B$a
[1] 5 5 5 5

$scores$list.B$b
[1] 6 6 6 6

$scores$list.B$c
[1] 7 7 7 7

I can select the list, but I cannot figure out how to perform an action on the list: lapply(megalist,'[[',"list.A")

I have tried:

names(megalist[[2]]$"list.A") <- rownames(mydf)

which only works on the second list scores and not on list.A contained within weights.

It does not work within both weights and scores lists for list.A.

CodePudding user response:

Try the following.
For each member of megalist assign new to its names attribute.

lapply(megalist, \(x, new) {
  names(x[["list.A"]]) <- new
  x
}, new = row.names(mydf))
  •  Tags:  
  • r
  • Related