Reputation: 3195
i have two tables. The first
char 1 2
<fct> <chr> <chr>
1 mild 2(2.00%) 2(2.00%)
2 moder 2(2.00%) 2(2.00%)
and the second
char `1 `2`
<fct> <chr> <chr>
1 mild 7 (25.00%) 7 (25.00%)
2 moder 7 (25.00%) 7 (25.00%)
I want to combine this tables in one. Namely, as output i expect
char 1 2
<fct> <chr> Y <chr> Y
mild 7(25.00%) 2(2.00%) 7(25.00%) 2(2.00%)
moder 7(25.00%) 2(2.00%) 7(25.00%) 2(2.00%)
How to do it?
Upvotes: 1
Views: 1100
Reputation: 47320
cbinding data frames like this can be unsafe, I would recommend a full join instead :
df3 <- merge(df1, df2, by="char", all = TRUE)
df3[c("char",sort(names(df3)[-1]))]
# char 1.x 1.y 2.x 2.y
# 1 mild 2 (2.00%) 7 (25.00%) 2 (2.00%) 7 (25.00%)
# 2 moder 2 (2.00%) 7 (25.00%) 2 (2.00%) 7 (25.00%)
Upvotes: 2
Reputation: 2067
Assuming your two tables look like this:
library(tidyverse)
df1 = data_frame(
char = factor(c('mild', 'moder')),
`1` = c('2 (2.00%)', '2 (2.00%)'),
`2` = c('2 (2.00%)', '2 (2.00%)'))
df2 = data_frame(
char = factor(c('mild', 'moder')),
`1` = c('7 (25.00%)', '7 (25.00%)'),
`2` = c('7 (25.00%)', '7 (25.00%)'))
# using base R
cbind(df1, df2)
#> char 1 2 char 1 2
#> 1 mild 2 (2.00%) 2 (2.00%) mild 7 (25.00%) 7 (25.00%)
#> 2 moder 2 (2.00%) 2 (2.00%) moder 7 (25.00%) 7 (25.00%)
# using tidyverse
bind_cols(df1, df2)
#> # A tibble: 2 x 6
#> char `1` `2` char1 `11` `21`
#> <fct> <chr> <chr> <fct> <chr> <chr>
#> 1 mild 2 (2.00%) 2 (2.00%) mild 7 (25.00%) 7 (25.00%)
#> 2 moder 2 (2.00%) 2 (2.00%) moder 7 (25.00%) 7 (25.00%)
I'd recommend the tidyverse one, since you won't end up with repeated column names (which'll really mess up further operations on this data), but you'll probably want to setNames
on it regardless.
Upvotes: 1