rjanitor

Add row totaling specified rows in r


I have the following problem (abstracted for simplicity).

w <- c('1st' , '2nd' , '3rd')
x <- c(1 , 2 , 5)
y <- c(50 , 17 , 22)
z <- c(55 , 20 , 14)
t <- data.frame(w , x, y , z)
t
    w x  y  z
1 1st 1 50 55
2 2nd 2 17 20
3 3rd 5 22 14

I would like to add a last row, "NewVal" , with the 3rd row less the 2nd row, i.e.,

NewVal , 3 , 5 , -6

There are several columns in the actual case so I would like to refer to columns w:z rather than individually. Janitor's adorn_totals looked promising but apparently you cannot specify the rows to be added. I tried tidyverse's add_row with an attempt to refer to the values I wanted to sum by indexing, but couldn't get that to work. I'm most familiar with tidyverse packages and syntax, and some functions of janitor, so a solution along those lines would be most helpful, but if that's not possible, anything would help. Thanks for any help!


Solution

  • library(dplyr)
    t %>%
      add_row(
        {.} %>% # helpful edit to avoid repeating `t`
          mutate(across(x:z, ~. - lag(.))) %>%
          slice(3) %>%
          mutate(w = "dif")
      )
    
    
        w x  y  z
    1 1st 1 50 55
    2 2nd 2 17 20
    3 3rd 5 22 14
    4 dif 3  5 -6