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?
>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
)
)