im trying to make a r code to calculate the "price" of imaginary products. It has unlimited amount but the price changes after you have bought 25 of it until the price is 20 then it stays unchanged forever. The prices are 2,5,8,12,15,20. Im trying to make a loop but my limited r knowledge keeps putting me in infinity loops. Here is my code:
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
CodePudding user response:
Since I had a bit to guess what you're trying to achieve here, here is a solution for my guess:
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