Home > OS >  Combine two dataframes with dplyr
Combine two dataframes with dplyr

Time:04-09

I would like to concatenate the values of two equally shaped data frames in R (df1 and df2) so that the final dataframe (df) contains all values separated by comma.

Here is an example

>df1
A B C
0 0 0
0 1 1

>df2
A B C
1 1 1
0 1 1

>df
A B C
0,1 0,1 0,1
0,0 1,1 1,1

Do you know any way to do it using dplyr?

CodePudding user response:

Base R approach -

df <- df1
df[] <- paste(as.matrix(df1), as.matrix(df2), sep = ",")
df

#    A   B   C
#1 0,1 0,1 0,1
#2 0,0 1,1 1,1

CodePudding user response:

Using the tidyverse you could first add an row id to each of your dataframes using e.g. lapply and tibble::rowd_to_column. Afterwards you could use bind_rows, group_by and summarise:

library(dplyr)

list(df1, df2) |> 
  lapply(tibble::rowid_to_column) |> 
  bind_rows() |> 
  group_by(rowid) |> 
  summarise(across(everything(), ~ paste(.x, collapse = ","))) |> 
  select(-rowid)
#> # A tibble: 2 × 3
#>   A     B     C    
#>   <chr> <chr> <chr>
#> 1 0,1   0,1   0,1  
#> 2 0,0   1,1   1,1

DATA

df1 <- data.frame(
  A = c(0, 0),
  B = c(0, 1),
  C = c(0, 1)
)

df2 <- data.frame(
  A = c(1, 0),
  B = c(1, 1),
  C = c(1, 1)
)

CodePudding user response:

Using Map:

#example data
df1 <- mtcars[1:2, 1:3]
df2 <- mtcars[3:4, 1:3]

data.frame(Map(paste, df1, df2, sep = ","))
#       mpg cyl    disp
# 1 21,22.8 6,4 160,108
# 2 21,21.4 6,6 160,258

# or mapply
#data.frame(mapply(paste, df1, df2, sep = ","))
  • Related