R update zero values in a data frame using a lookup table using the column names for the lookup

Viewed 67

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])
}
3 Answers

A base R option using Map

dfr[] <- Map(function(x, y) replace(x, x == 0, y), dfr, 
                            lku$E[match(names(dfr), lku$D)])

#    A    B     C
#1 0.5 5.00 1.000
#2 1.0 4.00 3.000
#3 2.0 3.00 0.003
#4 3.0 2.00 4.000
#5 4.0 1.00 2.000
#6 5.0 0.04 5.000

Another base R possibility could be:

sweep(dfr == 0, 2, t(lku[2]), "*") + dfr

    A    B     C
1 0.5 5.00 1.000
2 1.0 4.00 3.000
3 2.0 3.00 0.003
4 3.0 2.00 4.000
5 4.0 1.00 2.000
6 5.0 0.04 5.000

An option with base R

lku$E[col(dfr)] * (!dfr) + dfr
#   A    B     C
#1 0.5 5.00 1.000
#2 1.0 4.00 3.000
#3 2.0 3.00 0.003
#4 3.0 2.00 4.000
#5 4.0 1.00 2.000
#6 5.0 0.04 5.000
Related