Mahbub
Mahbub

Reputation: 21

merging columns using dplyr

Want to merge column elements to a single column

X <- tribble(
~X1,  ~X2, ~X3,
1, 2, 3, 4, 5, 6,
7, 8, 9)

apply(X, 1, function(x) paste0(x, collapse=""))

What would be dplyr version of this code?

Upvotes: 2

Views: 71

Answers (3)

Mikko Marttila
Mikko Marttila

Reputation: 11908

tidyr::unite() would be a natural fit if you want to modify the input data frame:

X <- tibble::tribble(
  ~X1, ~X2, ~X3,
  1, 2, 3,
  4, 5, 6,
  7, 8, 9
)

tidyr::unite(X, new, X1:X3, sep = "")
#> # A tibble: 3 x 1
#>   new  
#>   <chr>
#> 1 123  
#> 2 456  
#> 3 789

Created on 2019-08-30 by the reprex package (v0.3.0.9000)

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

A dplyr-purrr approach:

library(dplyr)
X %>% 
  rowwise() %>% 
purrr::map_dfr(.,paste0,collapse="")

Result:

# A tibble: 1 x 3
  X1    X2    X3   
  <chr> <chr> <chr>
1 147   258   369  

Or:

 X %>% 
   rowwise() %>% 
 purrr::map_chr(.,paste0,collapse="")
   X1    X2    X3 
"147" "258" "369" 

Upvotes: 1

Aur&#232;le
Aur&#232;le

Reputation: 12839

library(purrr)
library(dplyr)

X %>% 
  mutate(foo = pmap_chr(., paste0)) %>% 
  pull()
# [1] "123" "456" "789"

Or directly:

pmap_chr(X, paste0)

(though there is no more dplyr here :)


And a simpler base R version could be:

do.call(paste0, X)

Upvotes: 2

Related Questions