gpt4 book ai didi

r - for 循环和 if 语句来计算满足利润标准的月份

转载 作者:行者123 更新时间:2023-12-04 10:56:39 25 4
gpt4 key购买 nike

简单的循环问题,我知道有多种方法可以做到这一点,但为了学习 R,我试图以多种方式计算相同的答案。谢谢你的帮助!
问题计算税后利润高于当年平均水平的月数
数据

revenue <- c(14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50)
expenses <- c(12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96)
tax_rate <- .3

#monthly profit
profit_pre_tax <- revenue - expenses
profit_post_tax <- (revenue - expenses) * (1-tax_rate)
#Margin
profit_pre_tax_margin <- profit_pre_tax/revenue
profit_post_tax_margin <- profit_post_tax/revenue

#good and bad months
avg_profit <- mean(profit_post_tax)
all_avg_profit <- rep(avg_profit,length(profit_post_tax))
good_months <- 0
bad_months <- 0

#loop doesnt work getting an error that it only runs the if once, I also tried avg_profit but get the #same warning
for (i in 1:length(revenue)) {
if (profit_post_tax > all_avg_profit) {
good_months <- good_months + 1
} else {
bad_months <- bad_months + 1
}
}

#code works I get the correct answer of 6
good_m <- profit_post_tax[profit_post_tax > avg_profit]
num_good_m <- length(good_m)

最佳答案

在您的 for循环你会得到一个错误,因为你正在比较整个向量 profit_post_tax到整个向量 all_avg_profitall在每次迭代中。

要解决此问题,您可以执行以下操作:

for (i in 1:length(revenue)) {
if (profit_post_tax[i] > all_avg_profit[i]) {
good_months <- good_months + 1
} else {
bad_months <- bad_months + 1
}
}

你会得到你的答案。

替代

您可以通过执行以下操作变得非常简单:

gm <- sum(profit_post_tax > all_avg_profit)
bm <- sum(profit_post_tax <= all_avg_profit)

编辑:计算平均值

顺便说一句,你不需要做 all_avg_profit <- rep(avg_profit,length(profit_post_tax)) ,你可以直接去做你的 for环形:

for (i in 1:length(revenue)) {
if (profit_post_tax[i] > avg_profit) {
good_months <- good_months + 1
} else {
bad_months <- bad_months + 1
}
}

sum下面的例子:

gm <- sum(profit_post_tax > avg_profit)
bm <- sum(profit_post_tax <= avg_profit)

关于r - for 循环和 if 语句来计算满足利润标准的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com