Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all values using dplyr's across function [duplicate]

Tags:

r

dplyr

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"))
like image 542
chipsin Avatar asked Jun 04 '26 17:06

chipsin


1 Answers

Use :

library(dplyr)
df %>% mutate(across(everything(), ~replace(., . ==  -99 , "Removed")))

The .cols argument for across is by default everything() so this would work as well.

df %>% mutate(across(.fns = ~replace(., . ==  -99 , "Removed")))

However, the most simplest would be :

df[df == -99] <- 'Removed'
like image 65
Ronak Shah Avatar answered Jun 07 '26 06:06

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!