I constantly need to create new columns in r based on conditions of other columns. Because I work with time series data the columns the conditions are based on change for each time point. How do I loop an ifelse statement to create new variables when the ifelse statement is also changing for each new time point.
I usually just copy paste my ifelse statement but there is so much room for error. I would rather just use a loop or apply statement. For context for the code below we collect sputum at 13 different time points. We want to create 13 variables for those time points representing positive sputum. Sputum is considered "positive" based on the 2 conditions in the ifelse statement.
data$smear_bl <- ifelse(data$s_concafb_sputum_specimen_1== 0 | data$s_concafb_sputum_specimen_1==5, 0, 1)
data$smear_2 <- ifelse(data$s_concafb_sputum_specimen_2 == 0 | data$s_concafb_sputum_specimen_2 == 5, 0, 1 )
data$smear_3 <- ifelse(data$s_concafb_sputum_specimen_3 == 0 | data$s_concafb_sputum_specimen_3 == 5, 0, 1 )
data$smear_4 <- ifelse(data$s_concafb_sputum_specimen_4 == 0 | data$s_concafb_sputum_specimen_4 == 5, 0, 1 )
....
data$smear_mo5 <- ifelse(data$s_concafb_sputum_specimen_13 == 0 | data$s_concafb_sputum_specimen_13 == 5, 0, 1 )
I am hoping for 13 new variables as the above coding provides but through the use of a simpler statement!
Aucun commentaire:
Enregistrer un commentaire