Let's say I have two data frames I want to bind:
ds_a <- data.frame(
x = 1:6,
y = 5,
z = "4",
l = 2,
stringsAsFactors = FALSE
)
ds_b <- data.frame(
x = as.factor(1:6),
y = "5",
p = 2,
stringsAsFactors = FALSE
)
When I try to bind them I get the following error:
> bind_rows(ds_a, ds_b)
Error: Can't combine `..1$x` <integer> and `..2$x` <factor<4c79c>>.
Typically what I do to solve this is I convert all the columns in both data frames to a character, bind the two data frames, and then manually re-convert all the columns back to their original type.
Is there a way to simply coerce all the type collisions between ds_a and ds_b by automatically casting ds_b's columns to match ds_a (assuming they're named the same)?
More generally, I'd like a solution to automatically convert all the columns in ds_b to the type of ds_a wherever the column names match. And the solution should work if ds_b and ds_a don't share all the same columns (just filling with NA when columns don't exist in one, but do in another).
Here's the intended outcome:
ds_merged =read.table(text = 'x y z l p
1 1 5 4 2 NA
2 2 5 4 2 NA
3 3 5 4 2 NA
4 4 5 4 2 NA
5 5 5 4 2 NA
6 6 5 4 2 NA
7 1 5 NA NA 2
8 2 5 NA NA 2
9 3 5 NA NA 2
10 4 5 NA NA 2
11 5 5 NA NA 2
12 6 5 NA NA 2', header = TRUE, row.names = NULL)
> ds_merged
row.names x y z l p
1 1 1 5 4 2 NA
2 2 2 5 4 2 NA
3 3 3 5 4 2 NA
4 4 4 5 4 2 NA
5 5 5 5 4 2 NA
6 6 6 5 4 2 NA
7 7 1 5 NA NA 2
8 8 2 5 NA NA 2
9 9 3 5 NA NA 2
10 10 4 5 NA NA 2
11 11 5 5 NA NA 2
12 12 6 5 NA NA 2