I need to update x_eligible to 1, for all corresponding records of same study_id & site, where x == 1. This is to sort of to overwrite the values of x for the same records as study_id & site, whenever x_eligible is set to 1
Here is a reproducible code:
library(tidyverse)
newdata = data.frame(site = c('A','A','A','B','B','B','B'),
study_id = c(1,1,2,1,1,1,2),
x = c(0,1,0,0,NA,1,0),
x_eligible = c(0,1,0,0,0,1,0))
xEligibility2 <- function (x, siteid, studyID){
el = newdata %>% filter(site == siteid & study_id ==studyID & x_eligible==1)
if(exists("el"))
return(ifelse(nrow(el)>=1,1,0))
else
return(0)
}
newdata = newdata %>% mutate(
x_eligible = ifelse(apply(newdata, 1, xEligibility2, siteid=site, studyID=study_id) == 1, 1, 0)
)
And this is what I am getting as results on the x_eligible column:
x_eligible = c(1,1,1,1,1,1,1)
x_eligible is all being set to 1.
This is my expected output:
x_eligible = c(1,1,0,1,1,1,0)
I would appreciate any help to point out what I could be doing wrong.