Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading