首页 > 解决方案 > 如何在不指定列名的情况下将行添加到特定位置(索引)的小标题?(右)

问题描述

我有一个包含很多列的小标题。我需要在特定位置添加一行(例如在第 2 行之前)。如果不在值之前输入列名,如何做到这一点?

例如,这是我必须做的(想象更多的列,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)

这是我希望我能做的(返回错误,因为未指定列名):

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

我可以基于第一个 tibble 创建另一个 tibble 并使用 将其附加到旧的 tibble bind_rows,但在最后添加它,即我无法在第 2 行之前指定位置:

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

(目标是在 tbl1 中的两个值之间进行插值。)方法必须有效,即不能复制 tbl1。

标签: rrowtibble

解决方案


这是一个选项setNames

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

-输出

# A tibble: 3 x 2
#     V1    V2
#  <dbl> <dbl>
#1   1     3  
#2   1.5   3.5
#3   2     4  

推荐阅读