Home > Back-end >  Assigning dummy values based on previous occurrences in R - but also for the same year
Assigning dummy values based on previous occurrences in R - but also for the same year

Time:11-08

I want to do the same as in this question asked:

Assigning dummy values based on previous occurrences in R

BUT I want not only that the column "dummycount" takes the value 1 for the occurrence in the previous year in column "dummy" but also in the same year of the occurrence.

can you help me, please?

CodePudding user response:

Is this what you are trying to achieve?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df1 <- read.table(
  text = "nameID  titleID  year  dummy
          a       b 1999     1
          e       c 1999     1
          i       d 2000     0
          o       f 2000     0
          a       f 2000     1
          e       g 2001     0
          i       h 2002     0
          i       j 2003     0
          u       k 2003     1
          o       l 2004     1
          a       m 2004     0
          o       m 2004     0
          u       n 2005     0",
  header = TRUE
)

df1 %>% 
  group_by(nameID) %>%
  mutate(dummycount = ifelse(cummax(lag(dummy, default = 0)) >= 1 | cummax(dummy) >= 1, 1, 0))
#> # A tibble: 13 × 5
#> # Groups:   nameID [5]
#>    nameID titleID  year dummy dummycount
#>    <chr>  <chr>   <int> <int>      <dbl>
#>  1 a      b        1999     1          1
#>  2 e      c        1999     1          1
#>  3 i      d        2000     0          0
#>  4 o      f        2000     0          0
#>  5 a      f        2000     1          1
#>  6 e      g        2001     0          1
#>  7 i      h        2002     0          0
#>  8 i      j        2003     0          0
#>  9 u      k        2003     1          1
#> 10 o      l        2004     1          1
#> 11 a      m        2004     0          1
#> 12 o      m        2004     0          1
#> 13 u      n        2005     0          1

Created on 2021-11-08 by the reprex package (v2.0.1)

  • Related