Concatenate Two data.table Objects Vertically in R (Example Code)
In this article you’ll learn how to append two data.tables vertically in the R programming language.
Preparing the Example
install.packages("data.table") # Install data.table package library("data.table") # Load data.table |
install.packages("data.table") # Install data.table package library("data.table") # Load data.table
dt_A <- data.table(A = 10:5, # Create two data.tables B = letters[10:5]) dt_A # A B # 1: 10 j # 2: 9 i # 3: 8 h # 4: 7 g # 5: 6 f # 6: 5 e |
dt_A <- data.table(A = 10:5, # Create two data.tables B = letters[10:5]) dt_A # A B # 1: 10 j # 2: 9 i # 3: 8 h # 4: 7 g # 5: 6 f # 6: 5 e
dt_B <- data.table(A = 21:15, B = letters[21:15]) dt_B # A B # 1: 21 u # 2: 20 t # 3: 19 s # 4: 18 r # 5: 17 q # 6: 16 p # 7: 15 o |
dt_B <- data.table(A = 21:15, B = letters[21:15]) dt_B # A B # 1: 21 u # 2: 20 t # 3: 19 s # 4: 18 r # 5: 17 q # 6: 16 p # 7: 15 o
Example: Appending Two data.tables Vertically
dt_AB <- rbindlist(list(dt_A, dt_B)) # Concatenate two data.tables dt_AB # A B # 1: 10 j # 2: 9 i # 3: 8 h # 4: 7 g # 5: 6 f # 6: 5 e # 7: 21 u # 8: 20 t # 9: 19 s # 10: 18 r # 11: 17 q # 12: 16 p # 13: 15 o |
dt_AB <- rbindlist(list(dt_A, dt_B)) # Concatenate two data.tables dt_AB # A B # 1: 10 j # 2: 9 i # 3: 8 h # 4: 7 g # 5: 6 f # 6: 5 e # 7: 21 u # 8: 20 t # 9: 19 s # 10: 18 r # 11: 17 q # 12: 16 p # 13: 15 o
Further Resources
Below, you may find some further resources that are related to the content of this page.