Reputation: 598
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
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
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