1

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?

Sana Ali
  • 165
  • 1
  • 11

2 Answers2

1
library(tidyverse)

things2 <- things %>%
  spread(category, number) %>%
  mutate(diff = B - A) %>%
  gather(category, number, A:B) %>%
  select(category, things2do, number, diff) %>%
  arrange(things2do)
www
  • 38,575
  • 12
  • 48
  • 84
1

One way is to group the data by things2do and subsequently take an iterated difference.

library(dplyr)
things %>% 
  group_by(things2do) %>%
  mutate(diff = diff(number))
HNSKD
  • 1,614
  • 2
  • 14
  • 25