Inserting a new row without specifying column names in R using dplyr

Viewed 417

I want to insert a row into my dataframe but I don't want to write the columns names because that make the code too wordy. This is what I know it works:

# add_row ---------------------------------
df <- tibble(x = 1:3, y = 3:1)

df %>% add_row(x = 4, y = 0, .before = 3)
 A tibble: 4 x 2
       x     y
   <dbl> <dbl>
 1     1     3
 2     2     2
 3     4     0
 4     3     1

And this is what I wish it worked but it doesn't:

df %>% add_row(c(4,0), .before = 3)

Does anyone know if there is another way for doing that with dplyr?

3 Answers

Well, add_row requires name-value pairs but if you don't want to mention them explicitly you can automate the creation of it.

library(dplyr)

df %>% add_row(!!!setNames(c(4, 0), names(.)), .before = 3)

#      x     y
#  <dbl> <dbl>
#1     1     3
#2     2     2
#3     4     0
#4     3     1

We can use base R

rbind(df, c(4, 0))[c(1, 2, 4, 3),]
bind_rows(
  tibble(x = 1:3, y = 3:1),
  c(x = 4, y = 0)
)

Output:

x     y
<dbl> <dbl>
  1     1     3
2     2     2
3     3     1
4     4     0
Related