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:
This should do it:
library(dplyr)
df <- data.frame (Sale = c(100,200,500,150),
Cost = c(50,20,80,12),
Model = c("A","B","C","D"))
df %>%
mutate(across(c(Sale, Cost), ~.x/c(1,5,10)[as.numeric(cut(mean(Sale), breaks=c(-Inf, 50, 150, Inf)))]))
#> Sale Cost Model
#> 1 10 5.0 A
#> 2 20 2.0 B
#> 3 50 8.0 C
#> 4 15 1.2 D
Created on 2022-05-10 by the reprex package (v2.0.1)
CodePudding user response:
You could also use case_when
library(dplyr)
df %>%
mutate(Sale_2 = case_when(
mean(Sale) > 150 ~ Sale/10,
mean(Sale) > 50 ~ Sale/5
),
Cost_2 = case_when(
mean(Sale) > 150 ~ Cost/10,
mean(Sale) > 50 ~ Cost/5
))