Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between n and n-2 row for each group

Tags:

r

I want to identify the way to calculate the difference between every n and n-2 rows, for each group. Let suppose below is my data:

Month, Laptop, Sales
Jan, HP, 1000
Feb, HP, 2000
Mar, HP, 1300
April, HP, 5000
Jan, Samsung, 1200
Feb, Samsung, 2500
Mar, Samsung, 1100
April, Samsung, 4500

Now, I need the output like below, where i am taking the difference between every n and n-2 rows, and finding the result for each group based on its monthly data.

Month, Laptop, Sales, difference
Jan, HP, 1000 , NA
Feb, HP, 2000 , NA
Mar, HP, 1300 , 300
April, HP, 5000 , 3000,
Jan, Samsung, 1200 , NA
Feb, Samsung, 2500 , NA
Mar, Samsung, 1100 , -100
April, Samsung, 4500 , 2000
like image 769
Jay Avatar asked Mar 07 '23 08:03

Jay


2 Answers

Using dplyr::lag function, you can do

df <- df %>%
  group_by(Laptop) %>%
  mutate(difference = Sales - lag(Sales, 2))
df

# # A tibble: 8 x 4
# # Groups:   Laptop [2]
#   Month Laptop  Sales difference
#   <chr> <chr>   <int>      <int>
# 1 Jan   HP       1000         NA
# 2 Feb   HP       2000         NA
# 3 Mar   HP       1300        300
# 4 April HP       5000       3000
# 5 Jan   Samsung  1200         NA
# 6 Feb   Samsung  2500         NA
# 7 Mar   Samsung  1100       -100
# 8 April Samsung  4500       2000

Data

t <- "Month, Laptop, Sales
Jan, HP, 1000
Feb, HP, 2000
Mar, HP, 1300
April, HP, 5000
Jan, Samsung, 1200
Feb, Samsung, 2500
Mar, Samsung, 1100
April, Samsung, 4500"

df <- read.table(text = t, header = T, sep = ",", strip.white = TRUE)
like image 147
hpesoj626 Avatar answered Mar 13 '23 06:03

hpesoj626


One can use diff function along with dplyr to get the desired output.

lag = 2
df %>% group_by(Laptop) %>%
  mutate(difference = c(rep(NA,lag), diff(Sales, lag)))

# # A tibble: 8 x 4
# # Groups: Laptop [2]
#   Month Laptop  Sales difference
#   <chr> <chr>   <int>      <int>
# 1 Jan   HP       1000         NA
# 2 Feb   HP       2000         NA
# 3 Mar   HP       1300        300
# 4 April HP       5000       3000
# 5 Jan   Samsung  1200         NA
# 6 Feb   Samsung  2500         NA
# 7 Mar   Samsung  1100      - 100
# 8 April Samsung  4500       2000

Data:

df <- read.table(text =
"Month, Laptop, Sales
Jan, HP, 1000
Feb, HP, 2000
Mar, HP, 1300
April, HP, 5000
Jan, Samsung, 1200
Feb, Samsung, 2500
Mar, Samsung, 1100
April, Samsung, 4500",
header = TRUE, sep = ",", strip.white = TRUE, stringsAsFactors = FALSE)
like image 23
MKR Avatar answered Mar 13 '23 05:03

MKR