Recoding a variable using multiple conditions in a panel dataset

Hi! I hope you're enjoying the festive season.

Let's say I have a dataframe with one column (i.e. "Variable 1") containing binary values of 0 or 1. The second column (i.e. "Variable 2") is numeric and has a range of approx. 0-40. I would like to create a new column in this dataframe that is equal to 0 when Variable 1 is equal to 1 and when the value of Variable 2 is greater than what it was in the row directly above the applicable one (if these two conditions are not met, the new column can equal the value of Variable 1). May I ask how I would do this, using either base R or the tidyverse?

Thank you so much!

Hi @TheWusterWu,
Would this work for you?
suppressPackageStartupMessages(library(tidyverse))

#create example data
set.seed(1221)
df <- tibble(Variable1 = sample(c(0,1), 20, replace = TRUE), Variable2 = sample(1:40, 20, replace = TRUE))
#add column that shows 0 if this condition is met: 
# condition Variable1 == 1 AND current_value(Variable2) > previous_value(Variable2)
df %>% mutate(Variable3 = case_when(
  Variable1 == 1 & lag(Variable2, default = 0) < Variable2 ~ 0, 
  TRUE ~ as.double(Variable2)
  ))

Hello @xvalda,

Thank you so much for your kind response! This has worked for me.

Kind regards, and happy new year,
Yaning

Glad that it helped. And a happy and healthy new year to you as well.

This topic was automatically closed 7 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.