首页 > 解决方案 > 根据R中的相关列替换列值

问题描述

我目前正在处理具有地址和邮政编码列的数据集。我正在尝试通过查找具有相同地址的不同记录,然后将相应的邮政编码填充到无效的邮政编码来处理邮政编码中的无效/缺失数据。这样做的最佳方法是什么?

标签: rreplaceimputation

解决方案


步骤 1.使用非缺失地址和邮政编码构建排序的字典数据框。例如,在具有“address”列和“zip_code”列的数据框“df”中,您可以通过以下方式获得:

library(dplyr)
zip_dictionary <- na.omit(select(df, address, zip_code))
zip_dictionary <- distinct(zip_dictionary)

这假设您的数据中的每个“地址”只有一个唯一的“zip_code”值。如果没有,您需要确定要使用的值并相应地过滤或重新编码。

步骤 2.从 GitHub 安装 {elucidate} 包,并使用 translate() 函数使用从步骤 1 中提取的字典填写缺少的邮政编码:

remotes::install_github("bcgov/elucidate")
library(elucidate)

df <- df %>%
  mutate(zip_code = if_else(is.na(zip_code),
                            translate(address,
                                      old = zip_dictionary$address,
                                      new = zip_dictionary$zip_code)
                            )
         )

免责声明:我是 {elucidate} 包的作者


推荐阅读