Home > Back-end >  How to divide values in column by condition in R?
How to divide values in column by condition in R?

Time:05-12

I have code which divides the Sales column by 10 if the mean of sales is more than 150, else if the mean > 80, values are divided by 5 or keep the same in case < 80

df <- data.frame (Sale  = c(100,200,500,150),
                  Cost = c(50,20,80,12),
                  Model = c("A","B","C","D"))

df$Sale = df$Sale
if(mean(df$Sale)>150){
df$Sale = df$Sale/10
}else if(mean(df$Sale)>50){
df$Sale = df$Sale/5
}

However, I have another numerical column 'Cost' and want to do the same based on condition of sales, something like this:

 df[,Sales,Cost] = df[,Sales,Cost]
    if(mean(df$Sale)>150){
    df[Sales,Cost] = df[SalesCost]/10
    }else if(mean(df$Sale)>50){
    df[Sales,Cost] = df[Sales,Cost]/5
    }

CodePudding user response:

You can use dplyr::across to do the same function over multiple columns:

library(dplyr)
df %>% 
  mutate(across(c(Sale, Cost), ~ case_when(Sale > 150 ~ .x/10,
                                           Sale > 50 ~ .x/5,
                                           TRUE ~ .x)))

#  Sale Cost Model
#1   20 10.0     A
#2   20  2.0     B
#3   50  8.0     C
#4   30  2.4     D
  • Related