简体   繁体   中英

Add a new column in R based on other columns

I'm trying to clean up a data sheet that has multiple test results. We're considering a positive from any of the results to mean the person is positive. So I'm trying to create a code where if any of the test results are positive, then the diagnosis is positive. If there are no positives and at least one negative, then the diagnosis is negative (ex. Patients 4, 5 and 6). I also want to omit rows where there are no results (ie. NA) for all of the rows (ex. Patient 8). Can anyone help me with this? I tried this ifelse statement, but it's not working

practice$Diagnosis = ifelse((testresult_1 == "1"|testresult_2 == "1"|testresult_3 == "1"), "Positive", "Negative")
Patient ID     testresult_1   testresult_2    testresult_3  Diagnosis
1                Positive      Negative        Negative     Positive
2                Positive      Positive        Negative     Positive
3                Negative      Negative        Positive     Positive
4                Negative      Negative        Negative     Negative
5                Negative      Negative        NA           Negative
6                Negative      NA              NA           Negative
7                Positive      NA              NA           Positive
8                NA            NA              NA            NA

You can use rowSums :

cols <- grep('testresult', names(df))
practice$Diagnosis <- ifelse(rowSums(practice[cols] == 'Positive', 
                              na.rm = TRUE) > 0, "Positive", "Negative")
#Turn all NA to 0
practice$Diagnosis[rowSums(!is.na(practice[cols])) == 0] <- NA
practice
#  PatientID testresult_1 testresult_2 testresult_3 Diagnosis
#1         1     Positive     Negative     Negative  Positive
#2         2     Positive     Positive     Negative  Positive
#3         3     Negative     Negative     Positive  Positive
#4         4     Negative     Negative     Negative  Negative
#5         5     Negative     Negative         <NA>  Negative
#6         6     Negative         <NA>         <NA>  Negative
#7         7     Positive         <NA>         <NA>  Positive
#8         8         <NA>         <NA>         <NA>      <NA>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM