Problems with ifelse fuction with conditions based on a previous row, lead/ lag functions

Hi there,
For my dissertation I´m trying to create a new variable in R with ifelse function based on multiple conditions, some of them in the previous row of the df. The df has been already grouped and arranged by specific variables.
The goal is to be able to say whether the location where each journey start and ends is an anchor or not.
trip purpose== 11 means "University" and is not coded for the variable journeystart used for the first two conditions.

My code right now looks like this:

glasgow_area$anchor_start = ifelse(glasgow_area$journeystart=="Home"| 
                                   glasgow_area$journeystart=="Work" |
                                   lead(glasgow_area$purpose_trip)==11, "anchor start", "not anchor")

I do not get any warning but the variable "anchor_start in the row that follows the one with purpose_trip==11 is labeled as "not anchor" instead of "anchor start".
Is here the lead function wrong?

I would be so thankful if someone has an idea on what to do!

what you are doing will not respect 'groupings'.
to leverage dplyr groupings, you will need to stay within dplyr context.
consider the example :

(example_df <- data.frame(
  vals = c(1,2,3,4)

(example_df_bad <- group_by(example_df,

example_df_bad$leadval <- lead(example_df_bad$vals)

(example_df_good <- group_by(example_df,

(example_df_good <- mutate(example_df_good,

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