How to get a difference between a value and his previous based on 2 columns

#Difference between a value and his previous based on 2 columns

df <- data.frame(presence = c(1,2,5,8,10, 15, 20),
location = c("BO", "BO", "BO", "MO", "MO", "MO", "MO"),
year = c(2012, 2012, 2012, 2012, 2012, 2013, 2013))
df

df$diff <- ave(df$presence, factor(df$location&df$year), FUN = function(x) c(NA, diff(x)))

I'm trying to get the difference between values in the "presence" column, just if values share the same "location" and "year".

By running df$diff I receive this error: Error in df$location & df$year :
operations are possible only for numeric, logical or complex types

How can I do it?
Thanks in advance

maybe this

df <- data.frame(presence = c(1,2,5,8,10, 15, 20),
                 location = c("BO", "BO", "BO", "MO", "MO", "MO", "MO"),
                 year = c(2012, 2012, 2012, 2012, 2012, 2013, 2013))
df
library(tidyverse)

group_by(df,
         location,year) |> reframe(
           diff_presence = diff(presence)
         )

Perfect :slight_smile: it was exactly what i need!
Thanks a lot

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.