gpt4 book ai didi

r - 如何在不指定列名的情况下将行添加到特定位置(索引)的小标题? (右)

转载 作者:行者123 更新时间:2023-12-04 01:08:28 25 4
gpt4 key购买 nike

我有很多专栏。我需要在特定位置向它添加一行(例如,在第 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)

我可以根据第一个小标题创建另一个小标题,然后使用 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

关于r - 如何在不指定列名的情况下将行添加到特定位置(索引)的小标题? (右),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65554857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com