Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Merging two dataframes on one matching variable and retaining only one value for other disjoint variables

$
0
0

I have two dataframes I need to merge. The dataframes share all of the same columns. I am merging based on one shared variable, worker_ID. However, the other variables are often disjoint: one dataframe will have an "NA" and the other will have another value for a given variable. How can I merge in such a way that the output only retains the non-NA value?

x = worker_ID Var_1 Var_2 Var_3
    1         33    NA    NA
    2         NA    46    NA

y = worker_ID Var_1 Var_2 Var_3
    1         NA    75    NA
    2         NA    NA    66

z <- merge(x,y,by="worker_ID", all = TRUE)

This method does not work because instead of my desired output, z, I get a dataframe with two columns for each variable (one for the value of the variable in x and another for y). My desired output is z.

z = worker_ID Var_1 Var_2 Var_3
    1         33    75    NA
    2         NA    46    66

How can I tell R to let any non-NA entries supersede NA ones?


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>