SiH
SiH

Reputation: 1546

Concatenate tibbles with different columns

I want to concatenate tibbles,

  1. there are few common columns
  2. few columns with same name but different values
  3. one different column

I have create an example below, can someone please create the desired tibble

Thanks

library(tidyverse)

# common columns in both tibble
x <- c(1, 2, 3)
y <- c(2, 3, 4)

# common column name and different value for each tibble
v <- c(15, 10, 20)
# specific column to tibble
t_a <- c(4, 5, 6)

tbl_a <- tibble(x, y, v, t_a)


# common column name and different value for each tibble
v <- c(7, 11, 13)
# specific column to tibble
t_b<- c(9, 14, 46)

tbl_b <- tibble(x, y, v, t_b)


# concatenate tbl such output looks like this
x <- c(1, 2, 3, 1, 2, 3)
y <- c(2, 3, 4, 2, 3, 4)

v <- c(15, 10, 20, 7, 11, 13)

t <- c(4, 5, 6, 9, 14, 46)

name <- c("a", "a", "a", "b", "b", "b")

# desired output
tbl <- tibble(x, y, v, t, name)

Upvotes: 2

Views: 406

Answers (1)

akrun
akrun

Reputation: 887971

Here, we can bind the datasets together and use pivot_longer

library(dplyr)
library(tidyr)
bind_rows(tbl_a, tbl_b) %>% 
  pivot_longer(cols = c(t_a, t_b), names_to = c('.value', 'name'), 
     names_sep="_", values_to = 't', values_drop_na = TRUE)

-output

# A tibble: 6 x 5
#     x     y     v name      t
#  <dbl> <dbl> <dbl> <chr> <dbl>
#1     1     2    15 a         4
#2     2     3    10 a         5
#3     3     4    20 a         6
#4     1     2     7 b         9
#5     2     3    11 b        14
#6     3     4    13 b        46

Upvotes: 2

Related Questions