【问题标题】:Replacing column values based on related column in R根据R中的相关列替换列值
【发布时间】:2021-12-25 06:56:40
【问题描述】:

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

【问题讨论】:

  • merge 地址可能有用
  • @R.Schifini 不会合并合并单独的记录?
  • 阅读minimal reproducible example。展示与您所面临的情况类似的情况。我们还没有真正建立答案的基础。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: r replace imputation


【解决方案1】:

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

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} 软件包的作者

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多