Amin Shn
Amin Shn

Reputation: 598

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

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?

Upvotes: 3

Views: 1352

Answers (3)

TarJae
TarJae

Reputation: 79286

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

Upvotes: 1

akrun
akrun

Reputation: 887951

We can use base R

rbind(df, c(4, 0))[c(1, 2, 4, 3),]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

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

Upvotes: 5

Related Questions