jeudi 12 mars 2020

Conditional mutate with if else list of character vectors %in% vector of variables. Including test data

I'm sorting a data frame, where there are many different diagnostics, i.e. variables v1,v2,v3. The diagnostic tests can give categorical results, such as "Sick", "Sick2", or "nosick". The patients have undergone these diagnostics several consecutive years - "year".

I want to create a new variable, "Eval", which would class the patients as sick (1) if any single one or more of the diagnostic variables include a positive response, i.e. "Sick" or "Sick2" otherwise the patient is not sick (0)

testframe %>% group_by(year) %>% mutate(Eval=ifelse(any(sickvars %in% sickv)==TRUE,1,0))

However, the above call evaluates also years in which there are no positive responses as 1.

I've had no success either with:

testframe %>% group_by(year) %>% mutate(if(any(sickvars %in% sickv)==TRUE){Eval <- 1} else {Eval <- 0})

Here's a testing frame to use.

#Create testframe
v1 <- c("Sick","nosick","nosick","nosick","nosick")
v2 <- c("nosick","nosick","Sick2","nosick","nosick")
v3 <- c("nosick","Sick","Sick","nosick","nosick")

sickv <- c("Sick","Sick2")
sickvars <- c(v1,v2,v3)
year <- c(1,2,3,4,5)
testframe <- data.frame(sickid,v1,v2,v3)

Aucun commentaire:

Enregistrer un commentaire