for循环和if语句来计算符合利润标准的月份

问题描述 投票:2回答:1

简单循环问题,我知道有多种方法可以做到这一点,但是为了学习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)
r for-loop if-statement countif
1个回答
2
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.