I would like to be able to replace zero values in a data frame using a lookup table of replacement values, where the replacement value is different for each column. Trust that the simple example below explains the problem and the desired outcome.
# Dummy data frame
A <- seq(0,5,1)
B <- seq(5,0,-1)
C <- c(1,3,0,4,2,5)
dfr<-data.frame(A,B,C)
A B C
0 5 1
1 4 3
2 3 0
3 2 4
4 1 2
5 0 5
# Lookup table with replacement values
D <- c('A','B','C')
E <- c(0.5,0.04,0.003)
lku <- data.frame(D,E)
D E
A 0.500
B 0.040
C 0.003
# Desired answer
A B C
0.50 5.00 1.000
1.00 4.00 3.000
2.00 3.00 0.003
3.00 2.00 4.000
4.00 1.00 2.000
5.00 0.04 5.000
So if zero is found in column A when using the lookup table the zero and replaced by 0.50, but for column B the zero is replaced by 0.04 and so on. I'm not sure where to start with this one other than going through the columns one by one using a loop and pointing to the respective row of the lookup table?
Update
I gave the looping solution a try could not get this to work - an explanation of why not would be helpful.
for(i in 1:3){
ifelse(dfr[ ,i] == 0, lku[i,2], dfr[ ,i])
}