I need to conditionally transcode my data frame d
according to the search vector.
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
- This is a wide frame of data that I went through reshape
. I need to recode any NAs
in each column Apple
, Banana
and Carrot
up 0
, if it pat
matches this column according to the lookup table. In this case d$Apple[5]
, d$Banana[4]
they will be transcoded to 0
.
I worked with recode
from dplyr
, but I have no idea how to find and transcode it, not to mention that it needs to be done on several columns ... There was another related post on transcoding variables in R using a lookup table , but it seems This does not apply to my problem. Can anyone help me out? Thank!
Edit
I tried the following :.
e <- melt(d, id.vars=c("pat", "gene"))
e %>% mutate(test=ifelse(lookup[as.character(pat)] == variable, replace(value, is.na(value), 0), value))
My code works partially. It was possible to transcode NA
to d$Apple[5]
, but not to d$Banana[4]
, because the search can only give the first value:
lookup["102"]
102
"Apple"
whereas I need my search in order to be able to display both "Apple" and "Banana" and to be able to convert NAs
, fulfilling each condition accordingly. Any ideas?