Search code examples
rdplyrtidyrpurrr

Replace the specified column contents in the data frame with the values in the specified vector


Here are the sample code

df <- data.frame(
  A = c(1, 2, 3, 4),
  B = c(5, 6, NA, 8),
  C = c(9, NA, -1, 11),
  D = c(-2, 13, 14, 15),
  E = c(16, -3, 18, NA)
)

replace_vec <- c(100, 200, 300)

I want to replace the column 3:5 which the value is NA or <=0 into the value in vetor replace_vec just like :

df %>%
  mutate(C = if_else(is.na(C) | C < 0, replace_vec[1], C),
         D = if_else(is.na(D) | D < 0, replace_vec[2], D),
         E = if_else(is.na(E) | E < 0, replace_vec[3], E))

too much if_else and not so general, maybe use map* or like

df %>%
  mutate(across(3:5, ~ifelse(is.na(.x) | .x < 0, replace_vec, .)))

# or
df %>%
 mutate_at(vars(1:3), ~ map2(.x, replace_values, ~ ifelse(.x < 0 | is.na(.x), .y, .x)))

they do not work...

How to make the code more general? Thanks a lot!


Solution

  • You may try

    names(replace_vec) <- c('C', 'D', 'E')
    
    df %>%
      mutate(across(3:5, ~ifelse(is.na(.x) | .x < 0, replace_vec[cur_column()], .x)))
    
      A  B   C   D   E
    1 1  5   9 200  16
    2 2  6 100  13 300
    3 3 NA 100  14  18
    4 4  8  11  15 300