我有一個類似這樣的資料集,它顯示了每種產品的價格:
df <- tribble(
~product_id, ~price,
'123', 35,
'445', 98,
'654', 194,
'135', 2000,
'156', 10,
)
我現在想根據以下條件對使用此公式的產品價格進行折扣:價格*(100 - 折扣率)/ 100
如果價格為 X,則對價格進行 Y% 的折扣
- 低于 10 美元:3%
- 10-20 美元:5%
- 20-30 美元:7%
- 30-90 美元:10%
- 90-190 美元:20%
- 190-2000 美元:30%
- 高于 2000 美元:50%
因此,所需的輸出將是這樣的:
df <- tribble(
~product_id, ~price, ~discount_rate, ~final_price,
'123', 35, 10, 31.5,
'445', 98, 20, 78.4,
'654', 194, 30, 135.8,
'135', 2000, 50, 1000,
'156', 10, 5, 9.5,
)
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
只需創建一列“discount_rate”,cut然后從折扣價中減去“價格”
library(dplyr)
df <- df %>%
mutate(discount_rate = as.integer(as.character(cut(price,
breaks = c(-Inf, 10, 20, 30, 90, 190, 2000, Inf),
labels = c(3, 5, 7, 10, 20, 30, 50), right = FALSE))),
final_price = price - (price * discount_rate/100))
-輸出
# A tibble: 5 × 4
product_id price discount_rate final_price
<chr> <dbl> <int> <dbl>
1 123 35 10 31.5
2 445 98 20 78.4
3 654 194 30 136.
4 135 2000 50 1000
5 156 10 5 9.5
uj5u.com熱心網友回復:
您可以創建一個折扣表。
library(fuzzyjoin)
library(dplyr)
discount_table <- data.frame(start = c(0, 10, 20, 30, 90, 190, 2000),
end = c(10, 20, 30, 90, 190, 2000, Inf),
discount = c(0.03, 0.05, 0.07, 0.1, 0.2, 0.3, 0.5))
discount_table
# start end discount
#1 0 10 0.03
#2 10 20 0.05
#3 20 30 0.07
#4 30 90 0.10
#5 90 190 0.20
#6 190 2000 0.30
#7 2000 Inf 0.50
加入它df使用fuzzyjoin并計算新價格。
fuzzy_left_join(df, discount_table, by = c('price' = 'start', 'price' = 'end'),
match_fun = c(`>=`, `<`)) %>%
mutate(final_price = price - (price * discount),
discount = discount * 100)
# product_id price start end discount final_price
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 123 35 30 90 10 31.5
#2 445 98 90 190 20 78.4
#3 654 194 190 2000 30 136.
#4 135 2000 2000 Inf 50 1000
#5 156 10 10 20 5 9.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/340861.html
上一篇:基于日期的總和值
下一篇:使用管道在回圈內生成圖
