r - 如何将 map2 与长度不相等的向量一起使用



问题

我正在尝试计算 1 美元到 200,000 美元之间的收入应缴纳的所得税,增量为 100 美元(2000 年值)。

我抓取了有关税率的信息,从而列出了 34 个数据框。

我有一个根据收入和适用税率计算应付税款的功能。

使用该函数,我想生成一个显示应纳税额的向量:

  1. 对于每个收入水平(2000年值)
  2. 每套(34套费率)

如果我能在数据帧/tibble 中返回此输出,那就太好了。

数据

#This scrapes the website of the tax administrator and returns a list of tidy data frames showing tax rates for income years between 2016 and 1983
url <- "https://www.ato.gov.au/Rates/Individual-income-tax-for-prior-years/"
pit_sch <- url %>%
read_html() %>%
html_table() %>%
setNames(., url %>%
read_html() %>%
html_nodes("caption") %>%
html_text()) %>% 
map(.%>%
mutate(`Tax on this income` = gsub(",", "", `Tax on this income`), 
cumm_tax_amt = str_extract(`Tax on this income`, "(?<=^\$)\d+") %>% as.numeric(), 
tax_rate = str_extract(`Tax on this income`, "\d+.(\d+)?(?=(\s+)?c)") %>% as.numeric(), 
threshold = str_extract(`Tax on this income`, "(?<=\$)\d+$") %>% as.numeric()
)
) %>%
map(~drop_na(.x, threshold)) %>% 
map(function(x) { mutate_each(x, funs(replace(., is.na(.), 0))) })
#Defining income 
income <- seq(from = 1, to = 200000, by = 100)
#The function for calculating tax payable
tax_calc <- function(data, income) {
i <-tail(which(income >= data[, 5]), 1)
if (length(i) > 0) 
return(((income - data[i,5]) * (data[i,4]/100)) + data[i,3])
else
return(0)
}

我的尝试

> map2(pit_sch, income, tax_calc)
Error: Mapped vectors must have consistent lengths:
* `.x` has length 34
* `.y` has length 2000
enter code here

正确区分计算此值的不同income和年份。我建议让tax_calc函数返回一个具有incometax计算的tibble

library(tidyverse)
tax_calc <- function(data, income) {
i <-tail(which(income >= data[, 5]), 1)
if (length(i) > 0) 
return(tibble(income = income, 
tax = (income - data[i,5]) * (data[i,4]/100) + data[i,3]))
else
return(tibble(income = income, tax = 0))
}

由于您希望为每个pit_sch的所有incometax_calc,因此您可以使用

map(pit_sch,~map_df(income, tax_calc, data = .)) %>%  bind_rows(., .id = "id")

检查它是否得到tail(income)

map(pit_sch,~map_df(tail(income), tax_calc, data = .)) %>%  bind_rows(., .id = "id")
# A tibble: 204 x 3
#   id                             income    tax
#   <chr>                           <dbl>  <dbl>
# 1 Resident tax rates for 2016-17 199401 62962.
# 2 Resident tax rates for 2016-17 199501 63007.
# 3 Resident tax rates for 2016-17 199601 63052.
# 4 Resident tax rates for 2016-17 199701 63097.
# 5 Resident tax rates for 2016-17 199801 63142.
# 6 Resident tax rates for 2016-17 199901 63187.
# 7 Resident tax rates for 2015-16 199401 63277.
# 8 Resident tax rates for 2015-16 199501 63322.
# 9 Resident tax rates for 2015-16 199601 63367.
#10 Resident tax rates for 2015-16 199701 63412.
# … with 194 more rows

最新更新