[英]Conditional recode based on lookup vector
我需要根據查找向量有條件地重新編碼我的數據幀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")
d
是我通過reshape
獲得的寬數據幀。 如果pat
根據查找表匹配該列,我需要將每個Apple
, Banana
和Carrot
列中的任何NAs
重新編碼為0
。 在這種情況下, d$Apple[5]
和d$Banana[4]
將被重新編碼為0
。
我一直在dplyr
recode
,但是我不知道如何讓它進行查找和重新編碼,更不用說它必須在多個列上完成...還有一個關於在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))
我的代碼部分工作。 它成功地重新編碼了d$Apple[5]
的NA
d$Apple[5]
而不是d$Banana[4]
因為查找只能給出第一個值:
lookup["102"]
102
"Apple"
而我需要我的查找能夠輸出“Apple”和“Banana”,並能夠相應地轉換滿足每個條件的NAs
。 有任何想法嗎?
對不起,這里沒有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
也許有點不完整,但我已經設法通過循環創建一個可能的解決方案
for(i in 1:nrow(d)){
mtch <- lookup[which(d$pat[i] == names(lookup))] # Get lookup matches for row i
colnum <- which(colnames(d) %in% mtch) # Get column nr that matches lookup value
newval<-ifelse(is.na(d[i,colnum]),0,d[i,colnum]) # if it contains NA replace with 0
d[i,colnum]<-unlist(newval) # replace the values
}
產量
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
希望能幫助到你
我會使用長格式並使用dplyr
連接。
我首先回到如下所示的長格式:
library(tidyverse)
long_format <- d %>%
gather(fruit, value, -pat, -gene)
然后我將創建查找作為data_frame
,因此我們可以使用連接。
lookup <- tribble(~pat, ~fruit,
101, "Apple",
102, "Apple",
102, "Banana",
103, "Carrot")
使用right_join
意味着,我們保留查找中的所有組合。 然后,我們將缺少的值替換為0
並擴展回寬格式,以備您需要時使用。
long_format %>%
right_join(lookup) %>%
replace_na(replace = list(value = 0)) %>%
spread(fruit, value)
#> Joining, by = c("pat", "fruit")
#> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.