2017-03-14 32 views
1

這個問題是涉及到前面的話題: How to use custom function to create new binary variables within existing dataframe?在現有數據框中創建新的二進制變量的函數?

我想用類似的功能,但能夠使用矢量數據幀中指定ICD9診斷變量來搜索(例如,「diag_1」 「diag_2」, 「diag_1」 等)

我試圖

y<-c("diag_1","diag_2","diag_1") 

diagnosis_func(patient_db, y, "2851", "Anemia") 

,但我得到了以下錯誤:

Error in `[[<-`(`*tmp*`, i, value = value) : 
    recursive indexing failed at level 2 

下面是Benjamin從引用文章中的工作函數。但是,它一次只能從1個診斷變量中運行。最終,我需要創建一個新的二進制變量,通過查詢數據幀的25個診斷變量來指示患者是否具有特定的診斷。

* targetColumn位置是ICD9診斷變量「diag_1」 ......「diag_20」是一個我想輸入作爲載體

diagnosis_func <- function(data, target_col, icd, new_col){ 
    pattern <- sprintf("^(%s)", 
       paste0(icd, collapse = "|")) 

    data[[new_col]] <- grepl(pattern = pattern, 
         x = data[[target_col]]) + 0L 
    data 
} 

diagnosis_func(patient_db, "diag_1", "2851", "Anemia") 

這種非功能版本適用於多種診斷。但是我還沒有弄清楚如何在上面的函數版本中使用它。

pattern = paste("^(", paste0("2851", collapse = "|"), ")", sep = "") 

df$anemia<-ifelse(rowSums(sapply(df[c("diag_1","diag_2","diag_3")], grepl, pattern = pattern)) != 0,"1","0") 

任何幫助或指導如何讓這個功能的工作將不勝感激。

最佳, 阿爾比特

+0

可能更好地矢量喂'lapply'。像'lapply(y,function(i)diagnostics_func(data = df,target_col = i,icd = icd,newcol = i))''。也許你不得不嘮叨一下你的功能,但是這可能是更好的路線,我懷疑。 – lmo

+0

謝謝lmo!將嘗試這個 –

+0

阿爾比特,問題是本傑明的函數中的'grepl'將在你的數據框的一列工作。假設您有多個列,'target_col < - c(「diag_1」,「diag_2」,「diag_3」)'。爲了應用'grepl',你可以嘗試像這樣:'apply(data [target_col],2,function(x)grepl(pattern = pattern,x))''。讓我知道這個是否奏效。 – Dhiraj

回答

1

嘗試本傑明的功能的這款改裝版:

diagnosis_func <- function(data, target_col, icd, new_col){ 
    pattern <- sprintf("^(%s)", 
        paste0(icd, collapse = "|")) 

    new <- apply(data[target_col], 2, function(x) grepl(pattern=pattern, x)) + 0L 
    data[[new_col]] <- ifelse(rowSums(new)>0, 1,0) 
    data 
} 
+0

這工作!謝謝Dhiraj。 –

相關問題