dfテーブルの空白(欠落)郵便番号を、名前に基づいてziplessという別のテーブルの郵便番号と置き換えようとしています。 ベスト・アプローチは何ですか? 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'パッケージに含まれています。 –