I previously used the mutate_all
function in dplyr
to replace values in my data frame. I am trying to update my code to be able to accommodate the new across function but I am unsure how to update it so that it can perform the replace function.
Below is an example dataset.
df$A <- c(10,0,0,0,0,0,12,12,0,14,-99,14,-99,-99,16,16)
df$B <- c(10,0,0,0,12,12,12,12,0,14,-99,14,16,16,16,16)
df$C <- c(10,12,14,16,10,12,14,16,10,12,14,16,10,12,14,16)
A B C
10 10 10
0 0 12
0 0 14
0 0 16
0 12 10
0 12 12
12 12 14
12 12 16
0 0 10
14 14 12
-99 -99 14
14 14 16
-99 16 10
-99 16 12
16 16 14
16 16 16
The code I was previously using to replace a certain value (in this case -99) is below, and this worked successfully.
df %>% mutate_all(funs(replace(., .== -99, "Removed")))
A B C
10 10 10
0 0 12
0 0 14
0 0 16
0 12 10
0 12 12
12 12 14
12 12 16
0 0 10
14 14 12
Removed Removed 14
14 14 16
Removed 16 10
Removed 16 12
16 16 14
16 16 16
Below is how I tried to implement the across
function for everything
(this replaced all cells in the data frame with my desired replacement value; not just the instances of -99).
df %>% mutate(across(everything(), replace, -99 , "Removed"))