r - 根据R中的相关列替换列值
问题描述
我目前正在处理具有地址和邮政编码列的数据集。我正在尝试通过查找具有相同地址的不同记录,然后将相应的邮政编码填充到无效的邮政编码来处理邮政编码中的无效/缺失数据。这样做的最佳方法是什么?
解决方案
步骤 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} 包的作者
推荐阅读
- amazon-web-services - 如何在 AWS Cognito/Amplify 中的 federatedSignIn 中设置自定义属性
- javascript - 为一种形式传递了错误的图像 url,并从 Rails 4 中的部分形式更正到另一种形式
- python - Python 列表没有 isalpha()
- c# - 如何获取测试用例名称并将其用作文件名 NLog
- android - 使用 ktlint 的实时规则
- python - 从python中的位置参数创建属性
- python - 通过浏览器访问部署在 GCP Keubernetes 上的 Python Api
- pandas - Pandas - 将数据从单行拆分为多行
- django - 表单验证有时会失败并显示值错误
- python - selenium.common.exceptions.ElementNotInteractableException:消息:向 contenteditable div 元素发送文本时元素不可交互