Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify first change in value in a dataframe and ignore subsequent changes

Tags:

r

I want to use R to identify when a criteria is met for the first time and ignore subsequent changes. Example data:

df <- data.frame(response = c(1, 1, 1, 0, 1, 0))

Note: first response always starts with 1.

Expected output

f <- data.frame(response = c(1, 1, 1, 0, 1, 0), Threshold = c("no", "no", "no", "yes", "no", "no"))
like image 840
Benjamin Colbert Avatar asked Oct 27 '25 02:10

Benjamin Colbert


1 Answers

Set all to "no", then find the first 0, and set that one to "yes":

df$Threshold <- "no"
df$Threshold[ which(df$response == 0)[ 1 ] ] <- "yes"
# df
#   response Threshold
# 1        1        no
# 2        1        no
# 3        1        no
# 4        0       yes
# 5        1        no
# 6        0        no
like image 177
zx8754 Avatar answered Oct 28 '25 18:10

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!