Dplyr pipe: how to add a margin string calculating the total amount (for example, addmargins function - base)

My details:

data <- data.frame(column1 = c("A","B","C","D"), column2 = c(4, NA, NA, 1)) 

My pipe:

  library (dplyr) data2 <- data %>% filter (grepl("A|B|D", column1)) 

My question is: How can I (simply) continue my channel to add a line containing a common column2 (total = 5)?

+2
source share
1 answer

You can do:

 data2 <- data %>% filter (grepl("A|B|D", column1)) %>% rbind(., data.frame(column1="Total", column2=sum(.$column2, na.rm=T))) column1 column2 1 A 4 2 B NA 3 D 1 4 Total 5 
+5
source

All Articles