I'm struggling with the way to pick up the value of a variable based on the value of another variable in a different row in a data frame, within groups, and without usign for() loops. I'd be thankful if anyone could help me. These are a simplified form of my data:
library(data.table)
df<-data.table(personid<-c(101, 102, 103, 104, 105, 201, 202, 203, 301, 302, 401),
hh_id<-c(1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4),
fatherid<-c(NA, NA, 101, 101, 101, NA, NA, 201, NA, NA, NA),
cancer<-(1,0,0,0,0,0,0,0,0,0,1))
In my data frame, cases are grouped in households (hh_id), and there is a variable "fatherid" pointing at the person's father. I'd need to create a variable that indicates whether the person's father has cancer. This is: to pick up the value of the "cancer" variable from the fathers' register.
The expected result for this sample dataset would be:
fathercancer<-c(NA, NA, 1, 1, 1, NA, NA, 0, NA, NA, NA)
Any ideas on how to solve this without using a for loop?
Thanks in advance!