Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Referencing other items in a list before it is stored as an object

I have a list and would like to create a new list entry, d, by binding together the existing list entries as shown below:

library(data.table)

## this works fine
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3))

example_list[["d"]] <- rbindlist(example_list[c("a", "b", "c")])

Is it possible to create d at the same time as I create the original list? I would like to do something like this:

## this does not work
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3),
     "d" = rbindlist(.[c("a", "b", "c")]))

Edit: I need to explicitly reference previous list entries, thus something like this would not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

## ineligible
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3),
     "d" = data.frame(x = 1) %>% 
       rbind(data.frame(x = 2)) %>% 
       rbind(data.frame(x = 3)))

>Solution :

If we want to use a %>%, wrap it inside {}

library(dplyr)
library(data.table)
list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3)) %>%
     {c(., d = list(rbindlist(.[c("a", "b", "c")])))}

In base R, we can get the data from a list using within.list

within.list(list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3)), d <- rbindlist(list(a, b, c)))

-output

$a
  x
1 1

$b
  x
1 2

$c
  x
1 3

$d
   x
1: 1
2: 2
3: 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading