R关于列、变量和表的新手问题

  • 本文关键字:新手 问题 变量 于列 r
  • 更新时间 :
  • 英文 :


我是SAS用户,刚刚开始使用r。

我想计算纳税等级,我知道这是一个经典的问题,但是很难理解/掌握使用r的要点。

我想生成从1到1m的序列,然后根据序列值计算所支付的税。我知道在SAS中,它将简单地是税收=收入*税率与if-else从句,我如何使用R实现这一点?

我看到了一个基本函数:

income_tax <- function(income) {
# Calculate income tax liability based on income
#
# Returns the amount of income tax owed

if (income > 0 & income <= 9875) {
tax = 987.5
} else if (income > 9875 & income <= 40125) {
tax = 9875 + (income - 9875) * .12
} else if (income > 40125 & income <= 85525) {
tax = 4617.5 + (income - 40125) * 0.22
} else if (income > 85525 & income <= 163300) {
tax = 14605.5 + (income - 85525) * .34
} else if (income > 163300 & income <= 207350) {
tax = 323271.5 + (income - 163300) * .32
} else if (income > 307350 & income <= 518400) {
tax = 47367.5 + (income - 307350) * .35
} else if (income > 518400) {
tax = 156235 + (income - 518400) * .37
} 
return (tax)
}

但是这个函数只输出一个值?我不能操作收入变量的整个序列,至于它在SAS中是如何运作的。我怎样才能更好地理解这些背后的思想,有什么推荐的文本吗?多谢。

我们可以Vectorize函数

df1$newColumn <- Vectorize(income_tax)(df1$income)

最新更新