I have this sample data:
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)
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]))
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.
Appreciate any help, thank you.
Using only
dplyr
you could do the followingwhich results in
Note that this way the new row is added at the beginning rather than the end of the original dataframe.
If you want to add the new row at the end instead, use the following code (thanks to krlmlr for pointing this out)
which results in
Something like this then maybe:
Edit:
According to your comment, this will work:
Using the
.
will allowrbind
to findnvar3
Edit2:
Provide the new row as a list and it will maintain the column classes:
With
tibble
version 1.2 you can useadd_row()
https://blog.rstudio.org/2016/08/29/tibble-1-2-0/
One option utilizing
summarise_all()
andbind_rows()
could be:Or adding the row and then calculating the sum only for that last row using
if_else()
:Or an alternative to @Rickard's answer when the variables are not in global environment:
If someone is still looking for an universal solution I would be use:
P.S. I use tibble to keep character because a data frame converts them to factor and base::c "destroy" them