基于查找向量的条件重新编码

phu*_*ion 5 lookup r dplyr recode

我需要d根据查找向量有条件地重新编码我的数据帧。

dput(lookup)
structure(c("Apple", "Apple", "Banana", "Carrot"), .Names = c("101", "102", "102", "103"))
dput(d)
structure(list(pat = c(101, 101, 101, 102, 102, 103), gene = structure(1:6, .Label = c("a", 
"b", "c", "d", "e", "f"), class = "factor"), Apple = c(0.1, 0.2, 
0.3, 0.4, NA, NA), Banana = c(NA, NA, NA, NA, 0.55, NA), Carrot = c(NA, 
NA, NA, NA, NA, 0.6)), .Names = c("pat", "gene", "Apple", "Banana", 
"Carrot"), row.names = c(NA, -6L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

d是我通过的一个宽数据框reshape。我需要重新编写任何NAs内每一列AppleBananaCarrot0是否pat匹配,根据查找表列。在这种情况下,d$Apple[5]并且d$Banana[4]将被重新编码为0.

我一直在玩弄recodedplyr,但我不知道如何得到它的查找和重新编码,更何况,它必须建立在多个列做......有另一相关的职位重新编码的R参数与查找表但它似乎不适用于我的问题。有人可以帮我吗?谢谢!

编辑

我尝试了以下方法:

e <- melt(d, id.vars=c("pat", "gene"))
e %>% mutate(test=ifelse(lookup[as.character(pat)] == variable, replace(value, is.na(value), 0), value))
Run Code Online (Sandbox Code Playgroud)

我的代码部分工作。它成功地重新编码了NAind$Apple[5]但没有重新编码,d$Banana[4]因为查找只能给出第一个值:

lookup["102"]
    102 
"Apple" 
Run Code Online (Sandbox Code Playgroud)

而我需要我的查找能够输出“Apple”和“Banana”,并能够相应地转换NAs满足每个条件。有任何想法吗?

Gre*_*min 2

抱歉,dplyr这里没有,但代码相当简单。

for(i in unique(lookup)){
    need_to_replace = is.na(d[[i]]) & (d$pat %in% names(lookup[lookup %in% i]))
    d[[i]][need_to_replace] = 0
}

d

   pat gene Apple Banana Carrot
1 101    a   0.1     NA     NA
2 101    b   0.2     NA     NA
3 101    c   0.3     NA     NA
4 102    d   0.4   0.00     NA
5 102    e   0.0   0.55     NA
6 103    f    NA     NA    0.6
Run Code Online (Sandbox Code Playgroud)