r - 如何在不指定列名的情况下将行添加到特定位置(索引)的小标题?(右)
问题描述
我有一个包含很多列的小标题。我需要在特定位置添加一行(例如在第 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。
解决方案
这是一个选项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
推荐阅读
- javascript - JavaScript 试图读取对象在控制台上给我 undefined
- c# - 如何在 XML 而不是 JSON 中显示 SwaggerResponse
- python - pd.concat() 未在同一索引上合并
- objective-c - Xcode - 如何通过命令行更改文件的目标成员资格?
- javascript - 自引用对象分配中的键
- reactjs - React-Boostrap 模态未显示
- python - 如何从 PIL 中的函数中读取图像
- javascript - 如何使用 Java 脚本打印 JSON 文件
- python - 使用 Python 工厂习语
- php - php-amqplib 和 RabbitMQ 的死字?