identify change in row observation values

Viewed 32

I am interested in identifying individuals that go from a 0 to a .5 or a 1. Here is example data:

id     x
1      0 
1      1
1      1 
2      0
2     .5
2     .5
3      0  
3      0 

I want a new df that indicates whether or not each person moved from a 0 to .5 or 1. Something like this;

id    endorsed
1      TRUE
2      TRUE
3      FALSE  

I tried using ifelse for this, but I just can't get the code right. Does anyone have any suggestions?

3 Answers

An option to do a group by 'id', check for any values in 'x' that is a 0 and the next value is either 0.5 or 1 (using lead) (Assume that the precision is right)

library(dplyr)
df1 %>%
   group_by(id) %>%
   summarise(endorsed = any(x == 0 & lead(x) %in% c( 0.5, 1)))

-output

# A tibble: 3 x 2
#     id endorsed
#* <int> <lgl>   
#1     1 TRUE    
#2     2 TRUE    
#3     3 FALSE   

data

df1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L), x = c(0, 
1, 1, 0, 0.5, 0.5, 0, 0)), class = "data.frame", row.names = c(NA, 
-8L))

Since they always start with zero, you can just group and ask whether they ever hit 0.5 or 1:

df1 %>% group_by(id) %>% summarize(endorsed = any(x %in% c(0.5, 1)))

A base R option using aggregate

aggregate(
  cbind(endorsed = x) ~ id,
  df,
  function(v) head(v, 1) == 0 & tail(cummax(v), 1) %in% c(.5, 1)
)

gives

  id endorsed
1  1     TRUE
2  2     TRUE
3  3    FALSE
Related