Using bind_rows in a pipe

Viewed 580

Following a question I came across today, I would like to know how I can use bind_rows function in a pipe while avoiding duplication and NA values. Consider I have the following simple tibble:

df <- tibble(
  col1 = c(3, 4, 5),
  col2 = c(5, 3, 1), 
  col3 = c(6, 4, 9),
  col4 = c(9, 6, 5)
)

I would like to bind col1 & col2 row-wise with col3 & col4 so that I have a tibble with 2 columns and 6 observations. In the end changing the names of the columns to colnew1 and colnew2. But when I use bind_rows I got the following output with a lot of duplications and NA values.

df %>%
  bind_rows(
    select(., 1:2),
    select(., 3:4)
)

# A tibble: 9 x 4
   col1  col2  col3  col4
  <dbl> <dbl> <dbl> <dbl>
1     3     5     6     9
2     4     3     4     6
3     5     1     9     5
4     3     5    NA    NA
5     4     3    NA    NA
6     5     1    NA    NA
7    NA    NA     6     9
8    NA    NA     4     6
9    NA    NA     9     5

# My desired output would be something like this:

f1 <- function(x) {
  df <- x %>% 
    set_names(nm = rep(c("newcol1", "newcol2"), 2)) 
  bind_rows(df[, c(1, 2)], df[, c(3, 4)])
}

f1(df)
# A tibble: 6 x 2
  newcol1 newcol2
    <dbl>   <dbl>
1       3       5
2       4       3
3       5       1
4       6       9
5       4       6
6       9       5

I can get the desired output without a pipe but first I would like to know how I could use bind_rows in a pipe without getting NA values and duplications and second whether I could use select function in bind_rows as I remember once Hadley Wickham used filter function wrapped by bind_rows.

I would appreciate any explanation to this problem and thank you in advance.

1 Answers

Select the first two columns and bind_rows col3 col4 to col1 and col2 then use transmute

df1 <- df %>%
  select(col1, col2) %>% 
      bind_rows(
        df %>% 
          transmute(col1 = col3, col2 = col4)
      )

Results:

# A tibble: 6 x 2
   col1  col2
  <dbl> <dbl>
1     3     5
2     4     3
3     5     1
4     6     9
5     4     6
6     9     5
Related