Add a binary column to identify new observations

Viewed 20

I have a dataset which has tree measurements at time t1 and t2. These trees are identified by state, county, plot and tree number. There are some trees that have grown in the time interval between t1 and t2. So these trees are present in t2 but not in t1.

State   County   Plot    Tree     Meas_yr
1       9        1       1        t1 
1       9        1       2        t1
1       9        1       3        t1
1       9        1       1        t2
1       9        1       2        t2

I am trying to create a binary label which gives 1 to trees if they are present in only t2 and 0 to trees if they are present in both t1 and t2. I am hoping to create something like this.

State   County   Plot    Tree     Meas_yr  tree_survival
1       9        1       1        t1       0
1       9        1       2        t1       0
1       9        1       3        t1       0
1       9        1       1        t2       0
1       9        1       2        t2       0
1       9        1       4        t2       1
1       9        1       5        t2       1


I would really appreciate the help. Thanks in advance.

1 Answers

Here is a possible approach:

df %>%
  group_by(State, County, Plot, Tree) %>%
  mutate(prev_meas_yr = lag(Meas_yr, order_by = Meas_yr)) %>%
  mutate(tree_survival = ifelse(Meas_yr == "t2" & is.na(prev_meas_yr), 1, 0)) %>%
  select(-prev_meas_yr)

The idea is to add the previous record for each tree to its current record using lag. We can then set a binary flag based on the current value and the absence of a previous value (NA indicates a missing value).

Related