0

I want to generate an Indicator Variable that takes the value 1 for the Person 1, if in a ID group there exists a Person 3 otherwise 0.

The context: ID is unique to each household. Person 3 is a child of Person 1 in that household given by the ID. Want to generate HasAChild = 1 for Person = 1 when there exists a Person = 3 in the Household(given by the ID).

how it looks like

enter image description here

ID <- c(200, 200, 200, 211, 211, 222, 222, 222, 233, 233, 233, 233)
Person <- c(1, 3, 5, 1, 2, 1, 2, 3, 1, 2, 4, 5)
Is_A_Child <- c(0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Has_A_Child <- c(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)
df <- data.frame(ID, Person, Is_A_Child, Has_A_Child)
TTS
  • 1,818
  • 7
  • 16
  • 1
    Welcome to SO, when have a question in R, it is helpful to [make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1). – jessi Feb 27 '20 at 17:15
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Don't share data in an image because we can't copy/paste the values that way. – MrFlick Feb 27 '20 at 17:26

1 Answers1

0

Welcome. You can do this with mutate from dplyr. You just need to group them with ID

data %>% group_by(ID) %>% mutate ( HasAChild = ifelse("3" %in% Person & Person == 1,1,0))
Rhino8
  • 156
  • 1
  • 7