0

I want to find the difference in the values of the same type.

Please refer to the sample dataframe below:

df <- data.frame(
x = c("Jimmy Page","Jimmy Page","Jimmy Page","Jimmy Page", "John Smith", "John Smith", "John Smith",  "Joe Root", "Joe Root", "Joe Root", "Joe Root", "Joe Root"), 
y = c(1,2,3,4,5,7,89,12,34,67,95,9674 )
)

I would like to get the difference in the each value for e.g. Jimmy Page = 1 and Jimmy Page = 2, difference = 1.

And present NA for difference between dissimilar names.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
VRN
  • 15
  • 5

2 Answers2

0
library(tidyverse)
df <-
  data.frame(
    x = c(
      "Jimmy Page",
      "Jimmy Page",
      "Jimmy Page",
      "Jimmy Page",
      "John Smith",
      "John Smith",
      "John Smith",
      "Joe Root",
      "Joe Root",
      "Joe Root",
      "Joe Root",
      "Joe Root"
    ),
    y = c(1, 2, 3, 4, 5, 7, 89, 12, 34, 67, 95, 9674)
  )

df %>% 
  group_by(x) %>% 
  mutate(res = c(NA, diff(y))) %>% 
  ungroup()
#> # A tibble: 12 x 3
#>    x              y   res
#>    <chr>      <dbl> <dbl>
#>  1 Jimmy Page     1    NA
#>  2 Jimmy Page     2     1
#>  3 Jimmy Page     3     1
#>  4 Jimmy Page     4     1
#>  5 John Smith     5    NA
#>  6 John Smith     7     2
#>  7 John Smith    89    82
#>  8 Joe Root      12    NA
#>  9 Joe Root      34    22
#> 10 Joe Root      67    33
#> 11 Joe Root      95    28
#> 12 Joe Root    9674  9579

Created on 2021-09-14 by the reprex package (v2.0.1)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
0

You can use diff in ave.

df$diff <- ave(df$y, df$x, FUN=function(z) c(diff(z), NA))

df
#            x    y diff
#1  Jimmy Page    1    1
#2  Jimmy Page    2    1
#3  Jimmy Page    3    1
#4  Jimmy Page    4   NA
#5  John Smith    5    2
#6  John Smith    7   82
#7  John Smith   89   NA
#8    Joe Root   12   22
#9    Joe Root   34   33
#10   Joe Root   67   28
#11   Joe Root   95 9579
#12   Joe Root 9674   NA
GKi
  • 37,245
  • 2
  • 26
  • 48