Replace table values with a different set of lookup values


I have this dataframe called df_all_combinations that consists of a binary set of variables. I want to perform a lookup that where it finds a 1 it will replace it with the corresponding value of p depending on column position (so all 1's in column 1 should become 6 while all the 1's in column 9 should become 10). I want to do the same for w. I am not sure if I can do this with a mutate_all (I don't want to do this with various for loops).


df_initial <- data_frame(V1 = c(0,1),
                      V2 = c(0,1),
                      V3 = c(0,1),
                      V4 = c(0,1),
                      V5 = c(0,1),
                      V6 = c(0,1),
                      V7 = c(0,1),
                      V8 = c(0,1),
                      V9 = c(0,1)

df_all_combinations <- tidyr::expand(df_initial,V1,V2,V3,V4,V5,V6,V7,V8,V9)

p <- c(6, 6, 6, 6, 6, 6, 6, 8, 10) 
w <- c(3, 3, 3, 3, 3, 3, 3, 4, 5) 


I don't know if this is tidy enough, but at least it is a concise solution using mapply()

mapply(function(x, y) recode(x, y), df_all_combinations, p) %>% 

This is perfect. I didn't think of mapply() here. Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.