如何按R中的条件划分列中的值?
How to divide values in column by condition in R?
如果销售额的均值超过 150,我有代码将销售额列除以 10,否则如果均值 > 80,则值除以 5 或保持不变,以防 < 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
}
但是,我有另一个数字列 'Cost',我想根据销售情况做同样的事情,像这样:
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
}
您可以使用 dplyr::across
在多个列上执行相同的功能:
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
如果销售额的均值超过 150,我有代码将销售额列除以 10,否则如果均值 > 80,则值除以 5 或保持不变,以防 < 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
}
但是,我有另一个数字列 'Cost',我想根据销售情况做同样的事情,像这样:
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
}
您可以使用 dplyr::across
在多个列上执行相同的功能:
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