R:迭代插补\返回缺失值的函数

问题描述 投票:0回答:1

我是论坛的长期潜伏者,也是第一次发帖。对于我的帖子中的任何缺陷,我提前表示歉意。这是一个相当复杂的问题。

说明: 我有一个从各种来源收集的弗兰肯斯坦数据集。它包含一组不一致的公司 ID 变量,总共 18 个。假设我对一家公司有 5 个观察结果;我可能有 2、2、10 或 16 个标识符。有一些重叠;其余的都丢失了(

NA
)。我想找回丢失的 ID,所以理想情况下我有 18、18、18、18、18 或 16 个,具体取决于我为每个公司提供的覆盖范围。

问题描述: 现在,这是一个面板数据集,它增加了额外的复杂性。随着时间的推移,公司会合并、迁移和改变法律状态。并非所有 ID 变量都会以相同的方式对待它们,因此 ID 变量的 ID 代码可能会根据观察时间而变化。我想过滤掉这些案例,因为我无法确定要使用的正确 ID。

方法: 我尝试循环遍历每个变量的数据(假设我可以在填写空白时选择一些额外的匹配项)。我按每个 ID 变量对观察结果进行分组,并确定每个变量有多少个不同的观察结果。如果任何相应的 ID 变量有超过 1 个不同的观察结果,我认为存在冲突。如果只有 1,我认为不存在冲突并寻求填补缺失的值。但是,我的代码似乎无法正确循环,缺少潜在的可估算数据。

Sample Data:

### Not ID 1 should be imputable while ID 2 should not
data <- data.frame(ID = c(1, 1, NA, 2, NA, 2, 2, 2)
ID_Variable_1 = c(10, 10, NA, 20, 20, 20, 19, 18),   
ID_Variable_2 = c(NA, 8, 8, 16, 16, 16, NA, NA),   
ID_Variable_3 = c(NA, 8, 8, NA, 10, NA, NA, NA)   
ID_Variable_4 = c(A10, NA, NA, NA, NA, B12, B12, B12)
Current attempt:
### Extract vector of variables names
column_vector <- names(data) 

### Set Function to impute data
Impute_missing_data <- function(data, column_vector){   

#### Back-up data
temp_data <- data  

#### Loop through each variable
for (i in column_vector) {

#### Identify unique ID combinations, filter out those which contain conflicts
imputation_candidates <- temp_data %>%       
group_by_at(vars(i)) %>%       
summarise(across(everything(), ~ n_distinct(., na.rm = TRUE))) %>%       
filter(if_all(-i, ~ . <= 1), .preserve = TRUE)

#### Copy vector of IDs with imputable data
imputation_applying <- imputation_candidates\[\[i\]\] 

#### Update temporary data with imputable data. As all IDs are the same update based on the first non-NA
temp_data <- temp_data %>%       
group_by_at(vars(i)) %>%       
mutate(across(everything(), ~ ifelse(.x %in% imputation_applying & is.na(.), first(.x[!is.na(.x)]), .x))) %>% ungroup()   
}   

#### Return updated data
return(temp_data) 
}
Desired Output:
data_temp <- data.frame(ID = c(1, 1, 1, 2, NA, 2, 2, 2)
ID_Variable_1 = c(10, 10, 10, 20, 20, 20, 19, 18),   
ID_Variable_2 = c(8, 8, 8, 16, 16, 16, NA, NA),   
ID_Variable_3 = c(8, 8, 8, NA, 10, NA, NA, NA)   
ID_Variable_4 = c(A10, A10, A10, NA, NA, B12, B12, B12)
r loops imputation cross-reference
1个回答
0
投票
data %>% 
    rownames_to_column()%>%
    rows_patch(filter(fill(., everything(), .direction = 'downup'), ID == 1))%>%
    column_to_rownames()

Matching, by = "rowname"
  ID ID_Variable_1 ID_Variable_2 ID_Variable_3 ID_Variable_4
1  1            10             8             8           A10
2  1            10             8             8           A10
3  1            10             8             8           A10
4  2            20            16            NA          <NA>
5 NA            20            16            10          <NA>
6  2            20            16            NA           B12
7  2            19            NA            NA           B12
8  2            18            NA            NA           B12
© www.soinside.com 2019 - 2024. All rights reserved.