我在 R 中有一個函式,它接受代表商業折扣結構的字串并將它們轉換為數值乘數。例如,字串“50/20/15”僅表示原價優惠 50%,然后再優惠 20%,然后再優惠 15%。這相當于將原始價格乘以 (1 - 0.50)*(1 - 0.20)(1 - 0.15),等于 0.34。
我的功能如下。
disc_str_to_num <- function(string){
numstrings <- strsplit(string,"/")
nums <- mapply(as.numeric, numstrings)
prod(1 - nums/100)
}
在單個字串上可以按需要作業。
> disc_str_to_num("50/20/15")
[1] 0.34
不幸的是,這對于字串向量失敗了。
discount_vec <- c("50/10",
"50/10/10",
"50/10/15",
"50/10/20")
> disc_str_to_num(discount_vec)
Error in nums/100 : non-numeric argument to binary operator
我嘗試了該Vectorize功能的各種應用程式,但沒有成功。
如何修改我的函式以適用于字串向量?預期輸出是字串向量的分量值的數值向量。
uj5u.com熱心網友回復:
prod也應該在回圈內
sapply(strsplit(discount_vec, "/"), \(x) prod(1 - as.numeric(x)/100))
[1] 0.4500 0.4050 0.3825 0.3600
對于單個元素,mapply使用SIMPLIFY = TRUE,因此我們沒有任何問題,但是對于多個元素,它回傳 a list,因此最后一步不起作用
> list(c(1, 3), c(2, 4))/100
Error in list(c(1, 3), c(2, 4))/100 :
non-numeric argument to binary operator
如果我們使用 OP 的代碼,然后用另一個包裝mapply(或者可以mapply像顯示的那樣做sapply)
> disc_str_to_num <- function(string){
numstrings <- strsplit(string,"/")
nums <- mapply(as.numeric, numstrings)
mapply(\(x) prod(1 - x/100), nums)
}
>
> disc_str_to_num(discount_vec)
[1] 0.4500 0.4050 0.3825 0.3600
另一種選擇是閱讀data.framewith read.table,然后使用rowProdsfrommatrixStats
library(matrixStats)
rowProds(as.matrix(1- read.table(text = discount_vec,
header = FALSE, sep = "/", fill = TRUE)/100), na.rm = TRUE)
[1] 0.4500 0.4050 0.3825 0.3600
uj5u.com熱心網友回復:
像這樣使用矢量化:
Vectorize(disc_str_to_num)(discount_vec)
## 50/10 50/10/10 50/10/15 50/10/20
## 0.4500 0.4050 0.3825 0.3600
或者創建一個新的函式名然后呼叫它:
disc_str_to_num_vec <- Vectorize(disc_str_to_num)
disc_str_to_num_vec(discount_vec)
## 50/10 50/10/10 50/10/15 50/10/20
## 0.4500 0.4050 0.3825 0.3600
或重寫函式,如圖所示。請注意, strsplit 在此函式中創建一個元素串列,并且 [[1]] 獲取內容。
disc_str_to_num_vec2 <-
Vectorize(function(x) prod(1 - as.numeric(strsplit(x, "/")[[1]]) / 100))
disc_str_to_num_vec2(discount_vec)
## 50/10 50/10/10 50/10/15 50/10/20
## 0.4500 0.4050 0.3825 0.3600
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424853.html
下一篇:單獨的數字postgresql
