使用dplyr将行添加到数据框 [英] Add row to data frame with dplyr
本文介绍了使用dplyr将行添加到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下示例数据:
cvar <- c("2015-11-01","2015-11-02","All")
nvar1 <- c(12,10,5)
nvar2 <- c(7,5,6)
data <- cbind.data.frame(cvar,nvar1,nvar2)
我只想向其中添加新行包含nvar1&的和的data.frame nvar2和一个字符,因此使用基本RI只会使用
And I just want to add a new row to the data.frame containing the sums of nvar1 & nvar2 and a character, so with base R I would just use
data[nrow(data)+1,] <- c("add",sum(data[,2]),sum(data[,3]))
或更巧妙地使用lapply,但只是为了向您展示我在寻找什么。
or something more clever with lapply, but just to show you what I'm looking for.
我希望在管道环境中使用此简单命令,因此数据% >%...给了我以上的结果。
I would like this simple command within the pipe environment, so data %>% ... gives me the above outcome.
感谢任何帮助,谢谢。
推荐答案
类似这样的东西那么也许:
Something like this then maybe:
data %>%
rbind(c("add",sum(nvar1),sum(nvar2)))
# cvar nvar1 nvar2
#1 2015-11-01 12 7
#2 2015-11-02 10 5
#3 All 5 6
#4 add 27 18
编辑:
根据您的评论,这将起作用:
According to your comment, this will work:
data %>%
mutate(nvar3 = nvar1) %>%
rbind(c("add",sum(nvar1),sum(nvar2),sum(.$nvar3)))
使用。
将允许 rbind
查找 nvar3
Edit2:
将新行作为列表,它将保留列类:
Provide the new row as a list and it will maintain the column classes:
> str(
+ data %>%
+ mutate(nvar3 = nvar1) %>%
+ rbind(list("add",sum(nvar1),sum(nvar2),sum(.$nvar3)))
+ )
'data.frame': 4 obs. of 4 variables:
$ cvar : chr "2015-11-01" "2015-11-02" "All" "add"
$ nvar1: num 12 10 5 27
$ nvar2: num 7 5 6 18
$ nvar3: num 12 10 5 27
这篇关于使用dplyr将行添加到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文