Alton
Alton

Reputation: 147

Referencing nested list elements in r data.table ':=' (assignment by reference)

I'd like to access an object stored in a nested list as part of calculating a new data.table column, and the list indices that point to the object are saved in other data.table columns. Here's a simple example:

library(data.table)

list.test <- list("A" = list("AA" = 1, "BB" = 2), "B" = list("AA" = 3, "BB" = 4))

dt.test <- data.table(
  first.idx = rep(c("A", "B"), each=2),
  second.idx = rep(c("AA", "BB"), times = 2)
)

dt.test[ , result := list.test[[first.idx]][[second.idx]] ]

This returns the following error:

Error in list.test[[first.idx]] : no such index at level 2

The desired output is:

   first.idx second.idx result
1:         A         AA      1 
2:         A         BB      2
3:         B         AA      3
4:         B         BB      4

Upvotes: 2

Views: 258

Answers (1)

Joris C.
Joris C.

Reputation: 6234

Indexing into a nested list cannot be vectorized in such a way, (you try to call list.test[[c("A", "A", "B", "B")]][[c("AA", "BB", "AA", "BB")]]). Instead you can perform the indexing row-by-row (i.e. list.test[["A"]][["AA"]], etc.) using an individual grouping for each row:

dt.test[, result := list.test[[c(first.idx, second.idx)]], by = 1:nrow(dt.test)]
dt.test
#>    first.idx second.idx result
#> 1:         A         AA      1
#> 2:         A         BB      2
#> 3:         B         AA      3
#> 4:         B         BB      4

Upvotes: 1

Related Questions