Bind multiple data frames by row or column
bind.RdBind multiple data frames by row or column.
These functions are similar to do.call("rbind", list) or
do.call("cbind", list). See details for further usage.
Details
bind_rows() is used for a list of data frames that have the same
column names. bind_fill_rows() is used for a list of data frames that
have different column names (filling in missing rows with NA). See below for
how each handles column types:
| Function | Factor | List | Date | POSIXct | POSIXlt |
bind_rows | Supported | Supported | Supported | Supported | Supported |
bind_fill_rows | Coerced to integer | Supported | Coerced to integer | Coerced to integer | Error |
bind_rows() is faster than do.call("rbind", list), but much
slower than dplyr::bind_rows() and data.table::rbindlist() for
large lists. bind_fill_rows() is slower.
bind_cols() produces the same results as do.call("cbind", list),
but requires that each data frame have the same number of rows.
Before use, ensure data types are compatible per column and that each column
has a proper name. bind_rows() will convert factors to character if
columns of the same name have mixed character/factor types. If the same
column names have different factor levels or level ordering then test output
before using.
Examples
#----------------------------------------------------------------------------
# bind() examples
#----------------------------------------------------------------------------
library(bkdat)
l1 <- list(
data.frame(a = c(1, 2)),
data.frame(a = c(3, 4))
)
l2 <- list(
data.frame(a = c(1, 2)),
data.frame(b = c(3, 4))
)
l3 <- list(
as_df(
list(
POSIXct = as.POSIXct(c("2017-08-13", "2017-08-14")),
POSIXlt = as.POSIXlt(c("2017-08-13", "2017-08-14")),
Date = as.Date(c("2017-08-13", "2017-08-14")),
numeric = c(1, 2),
integer = 3:4,
character = letters[1:2],
missing = rep(c(1, NA)),
logical = rep(c(TRUE, FALSE)),
factor = factor(letters[1:2]),
list = replicate(2, list(a=data.frame(b = c(1, 2))))
)
),
as_df(
list(
POSIXct = as.POSIXct(c("2017-08-13", "2017-08-14")),
POSIXlt = as.POSIXlt(c("2017-08-13", "2017-08-14")),
Date = as.Date(c("2017-08-13", "2017-08-14")),
numeric = c(1, 2),
integer = 3:4,
character = letters[1:2],
missing = rep(c(1, NA)),
logical = rep(c(TRUE, FALSE)),
factor = factor(letters[1:2]),
list = replicate(2, list(a=data.frame(b = c(1, 2))))
)
)
)
bind_rows(l1)
#> a
#> 1 1
#> 2 2
#> 3 3
#> 4 4
bind_fill_rows(l2)
#> a b
#> 1 1 NA
#> 2 2 NA
#> 3 NA 3
#> 4 NA 4
bind_rows(l3)
#> POSIXct POSIXlt Date numeric integer character missing logical
#> 1 2017-08-13 2017-08-13 2017-08-13 1 3 a 1 TRUE
#> 2 2017-08-14 2017-08-14 2017-08-14 2 4 b NA FALSE
#> 3 2017-08-13 2017-08-13 2017-08-13 1 3 a 1 TRUE
#> 4 2017-08-14 2017-08-14 2017-08-14 2 4 b NA FALSE
#> factor list
#> 1 a 1, 2
#> 2 b 1, 2
#> 3 a 1, 2
#> 4 b 1, 2