我试图用名为zipless的另一个表中的zipcode替换df表中的空白(缺失)zipcode。 什么是最好的方法? for循环可能非常缓慢。R中的条件查找
我正在尝试这样的事情,但它不起作用。
df$zip_new <- ifelse(df, is.na(zip_new),
left_join(df,zipless, by = c("contbr_nm" = "contbr_nm")),
zip_new)
我能够使用这种方法使其工作,但我相信它不是最好的。 我首先在查找表中添加了一个新列,然后在下一步中根据需要选择性地使用它。
library(dplyr)
#temporarly renaming the lookup column in the lookup table
zipless <- plyr::rename(zipless, c("zip_new"="zip_new_temp"))
#adding the lookup column to the main table
df <- left_join(df, zipless, by = c("contbr_nm" = "contbr_nm"))
#taking over the value from the lookup column zip_new_temp if the condition is met, else, do nothing.
df$zip_new <- ifelse((df$zip_new == "") &
(df$contbr_nm %in% zipless$contbr_nm),
df$zip_new_temp,
df$zip_new)
什么是适当的方法来做到这一点?
非常感谢!
[重现数据(https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-例如)。即使是几个玩具数据集。你可以在你的一些上使用'dput'或者创建一些解释这个问题的东西。还包括你想要的输出。就目前来看,你的问题太模糊了。此外,请包括您正在使用的软件包的名称:'left_join'不是基本的R函数。 – lmo
使用coalesce()函数,即。 df $ zip_new < - coalesce(df $ zip_new,df $ zip_new_temp) –
请注意'coalesce'位于'dplyr'包中。 –