Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create dummy that equals 1 (and 0 otherwise) if an id appears only once? (in R)

structure(list(id = c(1L, 1L, 2L, 3L, 3L, 4L), hire_year = c(2017L, 
2017L, 2017L, 2017L, 2016L, 2016L)), class = "data.frame", row.names = c(NA, 
-6L))
  id hire_year
1  1      2017
2  1      2017
3  2      2017
4  3      2017
5  3      2016
6  4      2016

**Expected output**
  id hire_year dummy
1  1      2017     0
2  1      2017     0
3  2      2017     1
4  3      2017     0
5  3      2016     0
6  4      2016     1

How to create dummy that equals 1 (and 0 otherwise) if an id appears only once?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

With tidyverse, we can group by the id, then use the number of observations within an ifelse statement.

library(tidyverse)

df %>%
  group_by(id) %>%
  mutate(dummy = ifelse(n() == 1, 1, 0))

Or we could add the number of observations, then change the value based on the condition.

df %>% 
  add_count(id, name = "dummy") %>% 
  mutate(n = ifelse(n == 1, 1, 0))

Output

  id hire_year dummy
1  1      2017     0
2  1      2017     0
3  2      2017     1
4  3      2017     0
5  3      2016     0
6  4      2016     1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading