R - 舍入到最接近的不均匀间隔的自定义值

R - Round number to nearest unevenly spaced custom value

我正在尝试将连续年份四舍五入到最近的人口普查年份。不幸的是,在新西兰,人口普查之间的间隔并不总是一致的。例如。我想将 2000 年到 2020 年四舍五入到最接近的值 2001、2006、2013、2018。有没有办法在不诉诸一系列 if_elsecase_when 语句的情况下做到这一点?

您可以使用 sapply 求出两个向量之间的最小绝对差值。

假设你的向量是这样的:

census_years <- c(2001, 2006, 2013, 2018)
all_years <- 2000:2020

那么你可以这样做:

sapply(all_years, function(x) census_years[which.min(abs(census_years - x))])
#>  [1] 2001 2001 2001 2001 2006 2006 2006 2006 2006 2006 2013 2013 2013 2013 2013
#> [16] 2013 2018 2018 2018 2018 2018

reprex package (v0.3.0)

于 2020-12-09 创建

我们可以使用findInterval

census_year[findInterval(year_in_question, census_year)+1]
#[1] 2013

数据

census_year <- c(2001, 2006, 2013, 2018)
year_in_question <- 2012

通过找到年份和人口普查年份之间的最小差异,可以达到目的。矢量化留作练习...

require(magrittr)

census_year <- c(2001, 2006, 2013, 2018)
year_in_question <- 2012

abs(census_year - year_in_question) %>%  # abs diff in years
  which.min() %>%  # index number of the smallest abs difference
  census_year[.]   # use that index number

[1] 2013