dataframe - Selecting Rows in a Column Contingent on Two Variables in R -


i working data set contains multiple observations each prescription patient taking, many different patients. patients typically take 1 of several drugs, indicated own binary variables, drug1, drug2 , on.

i attempting pull out individuals have switched 1 drug other, i.e, have 1 in drug1 column , drug2, these occur in different rows.

i have attempted use newdata <- mydata[which(drug1 == 1 & drug2 == 1),] however, assumes 1's in same row, not.

is there way select patients have received both drugs, indicator variables in different rows?

thank

i believe solution asking using dplyr.

data <- data.frame(id = rep(c(1, 2, 3, 4), each = 2),                drug1 = c(1, 0, 0, 0, 0, 1, 1, 1),                drug2 = c(0, 1, 1, 1, 1, 0, 0, 0)                ) library(dplyr) data %>%   group_by(id) %>%   mutate(both_drugs = ifelse(any(drug1 == 1)  & any(drug2 == 1), 1, 0)) %>%   filter(both_drugs == 1) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -