[英]When using mutate() in dplyr, how to create a new column to be the sum or mean or several cells in the row without typing all the names?
[英]Inserting a new row without specifying column names in R using dplyr
我想在我的 dataframe 中插入一行,但我不想写列名,因为这会使代码过于冗长。 这就是我所知道的:
# 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
这就是我希望它起作用但它没有:
df %>% add_row(c(4,0), .before = 3)
有谁知道 dplyr 是否还有其他方法可以做到这一点?
好吧, add_row
需要名称-值对,但如果您不想明确提及它们,您可以自动创建它。
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
我们可以使用base R
rbind(df, c(4, 0))[c(1, 2, 4, 3),]
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.