для цикла и если заявление для расчета месяцев встречи прибыли Citeria - PullRequest
2 голосов
/ 01 декабря 2019

Проблема простого цикла, и я знаю, что есть несколько способов сделать это, но для изучения RI я пытаюсь вычислить один и тот же ответ несколькими способами. Спасибо за любую помощь!

Задача: рассчитать количество месяцев, в течение которых прибыль после уплаты налогов превышает средний показатель за год

Данные

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)

1 Ответ

2 голосов
/ 01 декабря 2019

В вашем цикле 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)
...