Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply cell in dataframe based on character

Tags:

dataframe

r

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))
like image 600
Afke Avatar asked Dec 06 '25 04:12

Afke


1 Answers

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))
like image 56
Jaap Avatar answered Dec 08 '25 18:12

Jaap