簡體   English   中英

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

代表 package (v0.3.0) 於 2020 年 12 月 9 日創建

我們可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM