Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R appending multiple data tables to a list

I need to append data.tables to an empty list in a way that by calling an index I get the entire data table. What I'm getting now is a list of the columns of the appended data tables so that at a particular index instead of getting a data table a get a column from one of those tables.

empty_list <- list()
dt<-data.table(c(1,2,3,4,5,6), c(4,5,6,7,8,9))
empty_list <- append(empty_list, dt)
empty_list[1]
like image 655
Dario Federici Avatar asked Dec 11 '25 07:12

Dario Federici


1 Answers

You want to append to empty_list another list(...) object. So:

empty_list <- list()
dt<-data.table(c(1,2,3,4,5,6), c(4,5,6,7,8,9))
empty_list <- append(empty_list, list(dt))
empty_list[1]
#[[1]]
#   V1 V2
#1:  1  4
#2:  2  5
#3:  3  6
#4:  4  7
#5:  5  8
#6:  6  9

As a simple representative example, consider that a data.table/data.frame is really just a fancy list.

is.list(data.table(3,4))
#[1] TRUE

str(append(list(1,2), list(3,4)))
#List of 4
# $ : num 1
# $ : num 2
# $ : num 3
# $ : num 4

str(append(list(1,2), list(list(3,4))))
#List of 3
# $ : num 1
# $ : num 2
# $ :List of 2
#  ..$ : num 3
#  ..$ : num 4
like image 125
thelatemail Avatar answered Dec 13 '25 20:12

thelatemail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!