'Is there a way in R to add a row underneath that calculates difference of above rows (tidyr/dplyr)?

I have a really simple question but am not able to figure out at all.

animal age
cat 12
dog 8

Normally I'd apply data %>% mutate(diff = age[1] - age[2]), but it adds a column beside, whereas I'd like a row underneath.

Below is the output I'd like. The difference row simply calculates the age of the cat minus age of the dog. So here are two example outputs:

animal age
cat 12
dog 8
diff 4
animal age
cat 10
dog 13
diff -3

Any help would be much appreciated. Thank you! Also to not, I'd like to not save the object. In other words, any way to do this through tidyverse would be best.



Solution 1:[1]

Hmm, how about:

bind_rows(df, df %>% summarize(animal = "diff", age = first(age) - last(age)))

Solution 2:[2]

You can use the add_row function from tibble.

library(tidyverse)

df <- read.table(header = T, text = "
animal  age
cat 10
dog 13")         

df %>% add_row(animal = "diff", age = diff(rev(df$age)))

  animal age
1    cat  10
2    dog  13
3   diff  -3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Spring
Solution 2 benson23