[英]Interpolate based on multiple conditions in r
初學者 r 用戶在這里。 我有不同行業分類和不同子區域的年度就業人數數據集。 對於某些觀察,員工人數為空。 我想通過線性插值(使用 na.approx 或其他一些方法)填充這些值。 但是,我只想在同一行業分類和子區域內進行插值。
例如,我有這個:
subregion <- c("East Bay", "East Bay", "East Bay", "East Bay", "East Bay", "South Bay")
industry <-c("A","A","A","A","A","B" )
year <- c(2013, 2014, 2015, 2016, 2017, 2002)
emp <- c(50, NA, NA, 80,NA, 300)
data <- data.frame(cbind(subregion,industry,year, emp))
subregion industry year emp
1 East Bay A 2013 50
2 East Bay A 2014 <NA>
3 East Bay A 2015 <NA>
4 East Bay A 2016 80
5 East Bay A 2017 <NA>
6 South Bay B 2002 300
我需要生成這個表,跳過對第五個觀察的插值,因為子區域和行業與之前的觀察不匹配。
subregion industry year emp
1 East Bay A 2013 50
2 East Bay A 2014 60
3 East Bay A 2015 70
4 East Bay A 2016 80
5 East Bay A 2017 <NA>
6 South Bay B 2002 300
像這樣的文章很有幫助,但我無法弄清楚如何調整解決方案以匹配兩列相同以進行插值而不是一列的要求。 任何幫助,將不勝感激。
我們可以通過na.approx
(來自zoo
)做一個小組
library(tidyverse)
data %>%
group_by(subregion, industry) %>%
mutate(emp = zoo::na.approx(emp, na.rm = FALSE))
# A tibble: 6 x 4
# Groups: subregion, industry [2]
# subregion industry year emp
# <fct> <fct> <dbl> <dbl>
#1 East Bay A 2013 50
#2 East Bay A 2014 60
#3 East Bay A 2015 70
#4 East Bay A 2016 80
#5 East Bay A 2017 NA
#6 South Bay B 2002 300
data <- data.frame(subregion,industry,year, emp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.