Home > database >  dplyr: Replace multiple values based on condition in a selection of columns
dplyr: Replace multiple values based on condition in a selection of columns

Time:05-04

I try to conditionally replace multiple values in a data frame.

In the following data set, I want to replace in columns 3:5 all values of 2 by "X" and all values of 3 by "Y", but only for measure == "led"

condition: measure == "led" replace: value "2" by "X" and value "3" by "Y" (in columns 3:5)

library(data.table)
dt <- data.table(measure = sample(c('cfl', 'led', 'linear', 'exit'), 20, replace=T),
                 site = sample(1:6, 20, replace=T),
                 space = sample(1:4, 20, replace=T),
                 qty = sample(1:6, 20, replace=T),
                 qty.exit = sample(1:6, 20, replace=T),
                 cf = sample(1:6, 20, replace=T))

Is there a simple dplyr solution for that? Many thanks!

CodePudding user response:

A dplyr solution:

library(dplyr)
dt %>%
  mutate(across(3:5, ~ ifelse(measure == "led", stringr::str_replace_all(
    as.character(.),
    c("2" = "X", "3" = "Y")
  ), .)))

Result:

   measure site space qty qty.exit cf
 1:     led    4     1   4        6  3
 2:    exit    4     2   1        4  6
 3:     cfl    1     4   6        2  3
 4:  linear    3     4   1        3  5
 5:     cfl    5     1   6        1  6
 6:    exit    4     3   2        6  4
 7:    exit    5     1   4        2  5
 8:    exit    1     4   3        6  4
 9:  linear    3     1   5        4  1
10:     led    4     1   1        1  1
11:    exit    5     4   3        5  2
12:     cfl    4     2   4        5  5
13:     led    4     X   Y        Y  4
...
  • Related