Search code examples
rdplyrrowdifferencealternate

Same difference in alternate rows per sub group


I have data frame where i need to find difference but for every alternate row the difference should stay same as the things to do are same like this:

enter image description here

but I have used this:

things <- data.frame( category = c("A","B","A","B","A","B","A","B","A","B"),
                      things2do = c("ball","ball","bat","bat","hockey","hockey","volley ball","volley ball","foos ball","foos ball"),
                      number = c(12,5,4,1,0,2,2,0,0,2))


    things %>% 
      mutate(diff = number - lead(number,order_by=things2do))

but it is not helpful,as I am getting this: enter image description here

Can i get some help here?


Solution

  • library(tidyverse)
    
    things2 <- things %>%
      spread(category, number) %>%
      mutate(diff = B - A) %>%
      gather(category, number, A:B) %>%
      select(category, things2do, number, diff) %>%
      arrange(things2do)