How do I multiply the Value by a factor 2 for each product having 2x?
Restaurant Product Value
1 a 3
1 b 2x 5
2 c 10
2 a 2x 2
I tried:
df = df %>%
mutate(Value=case_when(
Product =="2x"~ Value * 2,T~1))
Two options with base R:
# option 1:
df$Value <- df$Value * (grepl("2x", df$Product) + 1L)
# option 2:
ix <- grepl("2x", df$Product)
df$Value[ix] <- df$Value[ix] * 2L
which gives:
> df Restaurant Product Value 1 1 a 3 2 1 b 2x 10 3 2 c 10 4 2 a 2x 4
With dplyr:
df %>%
mutate(Value = Value * (grepl("2x", Product) + 1L))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With