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

Time:05-07

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.

CodePudding user response:

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

CodePudding user response:

Hmm, how about:

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