Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rows to a tibble at a specific place (index) without specifying column names? (R)

Tags:

r

row

tibble

I have a tibble with very many columns. I need to add a row to it at a specific location (e.g. before row 2). How can I do this without typing column names before the values?

E.g. this is what I must do (imagine more columns, V1, V2, V3, ...):

library(tidyverse)
tbl1 = tibble(V1=c(1,2), V2=c(3,4))
tbl1 %>% add_row(V1=1.5, V2=2.5, .before = 2)

This is what I wish I could do (returns error, since column names not specified):

library(tidyverse)
tbl1 = tibble(V1=c(1,2), V2=c(3,4))
tbl1 %>% add_row(c(1.5,3.5), .before = 2)

I can create another tibble based on the first one and append it to the old one using bind_rows, but that adds it at the end, i.e. I can't specify the location before row 2:

library(tidyverse)
tbl1 = tibble(V1=c(1,2), V2=c(3,4))
tbl2 = tbl1 %>% summarise_all(mean)
bind_rows(tbl1, tbl2)

(The goal is to interpolate between the two values in tbl1.) Method must be efficient, i.e. can't copy tbl1.

like image 545
PaulG Avatar asked Oct 27 '25 08:10

PaulG


1 Answers

Here is an option with setNames

library(tibble)
tbl1 %>% 
     add_row(!!! setNames(list(1.5, 3.5), names(.)), .before = 2)

-output

# A tibble: 3 x 2
#     V1    V2
#  <dbl> <dbl>
#1   1     3  
#2   1.5   3.5
#3   2     4  
like image 89
akrun Avatar answered Oct 29 '25 22:10

akrun