2017-08-13 45 views
0

我试图用名为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) 

什么是适当的方法来做到这一点?

非常感谢!

+1

[重现数据(https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-例如)。即使是几个玩具数据集。你可以在你的一些上使用'dput'或者创建一些解释这个问题的东西。还包括你想要的输出。就目前来看,你的问题太模糊了。此外,请包括您正在使用的软件包的名称:'left_join'不是基本的R函数。 – lmo

+1

使用coalesce()函数,即。 df $ zip_new < - coalesce(df $ zip_new,df $ zip_new_temp) –

+1

请注意'coalesce'位于'dplyr'包中。 –

回答

3

我建议使用match来抓住你需要的拉链。喜欢的东西:

miss_zips = is.na(df$zip_new) 
df$zip_new[miss_zips] = zipless$zip_new[match(
    df$contbr_nm[miss_zips], 
    zipless$contbr_nm 
)] 

无采样数据我不能完全确定你的列名,但这样的事情应该工作。

1

我只能为这类东西推荐data.table -package。但是你的一般方法是正确的。 data.table -package具有更好的语法,用于处理大型数据集。

data.table它可能是这样的:

zipcodes <- data.table(left_join(df, zipless, by = "contbr_nm")) 
zipcodes[, zip_new := ifelse(is.na(zip_new), zip_new_temp, zip_new)] 
+0

来自'dplyr'包的'left_join'? – www

+0

是的,对不起以上提及。这里你去:https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf – Trgovec

+0

对于'data.table'的答案,你可以使用'data.table '对于连接,你可以使用'zipcodes < - merge(df,zipless,by =“contbr_nm”,all.x = T)'或[如这里建议](https://stackoverflow.com/a/34600831/ 903061) – Gregor