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,n
One option utilizing summarise_all()
and bind_rows()
could be:
data %>%
bind_rows(summarise_all(., ~ if (is.numeric(.)) sum(.) else "add"))
cvar nvar1 nvar2
1 2015-11-01 12 7
2 2015-11-02 10 5
3 All 5 6
4 add 27 18
Or adding the row and then calculating the sum only for that last row using if_else()
:
data %>%
add_row(cvar = "add") %>%
mutate_at(-1, ~ if_else(row_number() == max(row_number()), sum(., na.rm = TRUE), .))
Or an alternative to @Rickard's answer when the variables are not in global environment:
data %>%
add_row(cvar = "add", nvar1 = sum(data$nvar1), nvar2 = sum(data$nvar2))