2016-04-29 68 views
0

我有2个数据集;一个包含关于患者的信息,另一个是医疗码在R中找到2组数据中的匹配字符串

patient <- data.table(ID = rep(1:5, each = 3), 
        codes = c("13H42", "1B1U", "Eu410", "Je450", "Fg65", "Eu411", "Eu402", "B110", "Eu410", "Eu50", 
          "1B1U", "Eu513", "Eu531", "Eu411", "Eu608") 
             ) 
code <- data.table(codes = c("BG689", "13H42", "BG689", "Ju34K", "Eu402", "Eu410", "Eu50", "JE541", "1B1U", 
         "Eu411", "Fg605", "GT6TU"), 
       term = c(NA)) 

列表中的code$term具有价值,但在这个例子中,他们会省略。

我想要的是patient中的指示器列,它显示了中的代码是否出现在patient$codes中。

patient 
    ID codes mh 
1: 1 13H42 TRUE 
2: 1 1B1U TRUE 
3: 1 Eu410 TRUE 
4: 2 Je450 FALSE 
5: 2 Fg65 FALSE 
6: 2 Eu411 TRUE 
7: 3 Eu402 TRUE 
8: 3 B110 FALSE 
9: 3 Eu410 TRUE 
10: 4 Eu50 TRUE 
11: 4 1B1U TRUE 
12: 4 Eu513 FALSE 
13: 5 Eu531 FALSE 
14: 5 Eu411 TRUE 
15: 5 Eu608 FALSE 

我的解决办法是使用grepl:

patient$mh <- mapply(grepl, pattern=code$codes, x=patient$codes) 

然而这并没有为code工作是不一样的长度,我得到了警告

Warning message: 
In mapply(grepl, pattern = code$codes, x = patient$codes) : 
    longer argument not a multiple of length of shorter 

所有解决方案完全匹配?

+0

你想要完全匹配吗? –

+0

@Kunal Puri是 – Lb93

+1

您确定您的预期产出是正确的吗?认为你可以做'耐心$ mh < - 耐心$ code%在%code $代码' – mtoto

回答

2

你可以这样做:

patient[,mh := codes %in% code$codes] 

更新:

正如Pasqui正确建议,为获得0和1,

可以进一步做:

patient[,mh := as.numeric(mh)] 
+1

然后'患者[,mh:= as.numeric(mh)]'因为他想要0s和1s :) – Pasqui

1

编辑:别人发布了更好的答案。我喜欢@moto自己的%1。更简洁,更高效。坚持与那些:)

这应该做到这一点。我已经使用了一个for循环,所以你可能会想出更有效率的东西。我也将循环分成几行,而不是将它们压缩成一个。这只是让你可以看到发生了什么:

for(row in 1:nrow(patient)) { 
    codecheck <- patient$codes[row] 
    output <- ifelse(sum(grepl(codecheck, code$codes)) > 0L, 1, 0) 
    patient$new[row] <- output 
} 

所以这只是一个通过患者列表中的一个去,使用grepl匹配检查,然后把结果(1匹配,0表示不匹配)回进入患者框架,作为一个新的专栏。

这就是你所追求的?

相关问题