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

How to change values based on if another column contains specific text?

I have a dataset where I need to change values for any device that does not contain the text "INV" to 0.

    
Device     Value
RGM        4279
INV A1     727
INV A2     3731
POA        73974

I figured something like this would work, but it doesn’t.

if (grepl(!"INV", df$Device, fixed = TRUE) {
  df$Value <- 0
}

Any ideas?

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

>Solution :

Base Solution

To modify things the way you originally intended, simply subscript df$Value to target the nonmatches, and overwrite then with <- 0:

df$Value[!grepl("INV", df$Device, fixed = TRUE)] <- 0

Tidy Alternative

Alternatively, if you want to work within tidyverse convention, this should do the trick with dplyr:

library(dplyr)

df <- df %>%
  # Mutate the column as a whole.
  mutate(
    Value = if_else(
      # Determine which values in the column do NOT (!) match the regex.
      !grepl("INV", Value, fixed = TRUE),
      # Overwrite any matches with 0; otherwise keep the original value.
      0, Value
    )
  )
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