我正在嘗試制作一個 r 代碼來計算price虛產品的數量。它的數量不限,但購買后價格會發生變化25。它永遠保持不變。價格是2,5,8,12,15,20。這是我的代碼:
n<-c(0:9999)
countchange<-seq(25,150, by=25)
price<-c(2,5,8,12,15,20)
for (n in 0:9999) {
if(n<countchange) {price=price[1]}
else{price}
}
pricechange<-function(n){
coinssum<-n*price
return(coinssum)
}
pricechange
uj5u.com熱心網友回復:
由于我有點猜測您在這里嘗試實作的目標,因此這是我猜測的解決方案:
library(tidyverse)
whatCaniAfford <- function(coins){
price <- tibble(price = c(2,5,8,12,15,20)) %>%
mutate(
treshold = cumsum(price*25),
budget = coins-treshold)
price %>%
mutate(afford = case_when(
coins <= 50 & price == 2 ~ floor(coins/2),
coins <= 50 & price > 2 ~ 0,
budget > 0 & price < 20 ~ 25,
budget > 0 & price == 20 ~ floor(lag(budget)/20),
budget < 0 ~ floor(lag(budget)/price)
)) %>%
filter(afford > 0) %>%
select(price, afford)
}
whatCaniAfford(coins = 1000)
# A tibble: 5 × 2
price afford
<dbl> <dbl>
1 2 25
2 5 25
3 8 25
4 12 25
5 15 21
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380649.html
