简单循环问题,我知道有多种方法可以做到这一点,但是为了学习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)
答案 0 :(得分: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)