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
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
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With