[英]Add a new column in R based on other columns
我正在嘗試清理具有多個測試結果的數據表。 我們正在考慮任何結果中的陽性表示該人是陽性的。 所以我正在嘗試創建一個代碼,如果任何測試結果為陽性,則診斷為陽性。 如果沒有陽性且至少有一個陰性,則診斷為陰性(例如患者 4、5 和 6)。 我還想省略所有行(例如患者 8)沒有結果的行(即 NA)。 誰能幫我這個? 我試過這個ifelse
語句,但它不起作用
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
您可以使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.