do.call("rbind", l) on
data.frames, but much faster.
rbindlist(l, use.names="check", fill=FALSE, idcol=NULL) # rbind(..., use.names=TRUE, fill=FALSE, idcol=NULL)
A list containing
Creates a column in the result showing which list item those rows came from.
Each item of
l can be a
NULL (skipped) or an empty object (0 rows).
rbindlist is most useful when there are an unknown number of (potentially many) objects to stack, such as returned by
rbind is most useful to stack two or three objects which you know in advance.
... should contain at least one
rbind(...) to call the fast method and return a
rbindlist(l) always returns a
data.table even when stacking a plain
list with a
data.frame, for example.
Columns with duplicate names are bound in the order of occurrence, similar to base. The position (column number) that each duplicate name occurs is also retained.
i does not have the same type in each of the list items; e.g, the column is
integer in item 1 while others are
numeric, they are coerced to the highest type.
If a column contains factors then a factor is created. If any of the factors are also ordered factors then the longest set of ordered levels are found (the first if this is tied). Then the ordered levels from each list item are checked to be an ordered subset of these longest levels. If any ambiguities are found (e.g.
green<blue), or any ordered levels are missing from the longest, then a regular factor is created with warning. Any strings in regular factor and character columns which are missing from the longest ordered levels are added at the end.
data.table containing a concatenation of all the items passed in.
# default case DT1 = data.table(A=1:3,B=letters[1:3]) DT2 = data.table(A=4:5,B=letters[4:5]) l = list(DT1,DT2) rbindlist(l)#> A B #> 1: 1 a #> 2: 2 b #> 3: 3 c #> 4: 4 d #> 5: 5 e# bind correctly by names DT1 = data.table(A=1:3,B=letters[1:3]) DT2 = data.table(B=letters[4:5],A=4:5) l = list(DT1,DT2) rbindlist(l, use.names=TRUE)#> A B #> 1: 1 a #> 2: 2 b #> 3: 3 c #> 4: 4 d #> 5: 5 e# fill missing columns, and match by col names DT1 = data.table(A=1:3,B=letters[1:3]) DT2 = data.table(B=letters[4:5],C=factor(1:2)) l = list(DT1,DT2) rbindlist(l, use.names=TRUE, fill=TRUE)#> A B C #> 1: 1 a <NA> #> 2: 2 b <NA> #> 3: 3 c <NA> #> 4: NA d 1 #> 5: NA e 2# generate index column, auto generates indices rbindlist(l, use.names=TRUE, fill=TRUE, idcol=TRUE)#> .id A B C #> 1: 1 1 a <NA> #> 2: 1 2 b <NA> #> 3: 1 3 c <NA> #> 4: 2 NA d 1 #> 5: 2 NA e 2# let's name the list setattr(l, 'names', c("a", "b")) rbindlist(l, use.names=TRUE, fill=TRUE, idcol="ID")#> ID A B C #> 1: a 1 a <NA> #> 2: a 2 b <NA> #> 3: a 3 c <NA> #> 4: b NA d 1 #> 5: b NA e 2