How to merge 2 dataframe by replacing NAN values

Hi R fans !
I have 2 dataframe :
df_1 : Keywords and Search Volume (and many NAN in Search Volume)
df_2 : Keywords (the ones concerned by NAN in df_1) and Search Volume

I would like to replace Search Volume with NAN in df_1 by Search Volume available in df_2

Any idea how to do such thing ?

Thanks a lot !

Something like that?

to_replace <- is.nan(df1$SearchVolume)
df1$SearchVolume[to_replace] <- df2$SearchVolume[to_replace]

That's if they have the same order. Else you need to sort or merge first:

df_merged <- merge(df1, df2, by=Keywords)
df_merged$newSearchVolume <- ifelse(! is.nan(df_merged$SearchVolume.x),
    df_merged$SearchVolume.x,
    df_merged$SearchVolume.y)

Not tested, there might be typos.

Hello Alexis,

Thank you for your reply
Well your suggestion leads me to the right solution, here it is :

df <- left_join(df1, df2, by="h1")
df$new_search_volume <- ifelse(is.na(df$search_volume),
df$Search.Volume,
df$search_volume)
"Search.Volume" data from df2
"search_volume" data from df1

It works well !
Thanks

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.