Minnow
Minnow

Reputation: 1811

Concatenate values in two data frames in R

Given two dataframes with the same column names:

a <- data.frame(x=1:4,y=5:8)
b <- data.frame(x=LETTERS[1:4],y=LETTERS[5:8])

>a 
 x y
 1 5
 2 6
 3 7
 4 8

>b
 x y
 A E
 B F
 C G
 D H

How can each column with the same name be concatentated?

Desired output:

cat_x cat_y
 1 A   5 E
 2 B   6 F
 3 C   7 G
 4 D   8 H

Tried so far, merging columns one at a time:

a$cat_x <- paste(a$x,b$x)
a$cat_y <- paste(a$y,b$y)

This approach works, but the real data has 40 columns (and will include multiple more dataframes). Looking for a more efficient method for larger dataframes.

Upvotes: 1

Views: 558

Answers (2)

PaulS
PaulS

Reputation: 25313

Another possible solution, using purrr::map2_dfc:

library(tidyverse)

map2_dfc(a,b, ~ str_c(.x, .y, sep = " ")) %>% 
  rename_with(~ str_c("cat", .x, sep = "_"))

#> # A tibble: 4 × 2
#>   cat_x cat_y
#>   <chr> <chr>
#> 1 1 A   5 E  
#> 2 2 B   6 F  
#> 3 3 C   7 G  
#> 4 4 D   8 H

Upvotes: 1

akrun
akrun

Reputation: 886938

We may use Map to do this on a loop

data.frame(Map(paste, setNames(a, paste0("cat_", names(a))), b, 
     MoreArgs = list(sep = "_")))

-output

   cat_x cat_y
1   1_A   5_E
2   2_B   6_F
3   3_C   7_G
4   4_D   8_H

Used sep above in case we want to add a delimiter. Or else by default it will be space

data.frame(Map(paste, setNames(a, paste0("cat_", names(a))), b ))
  cat_x cat_y
1   1 A   5 E
2   2 B   6 F
3   3 C   7 G
4   4 D   8 H

Upvotes: 2

Related Questions