Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 dataframes with duplicate columns?

I have an empty dataframe as such:

a <- data.frame(x = rep(NA,10))

which gives the following:

    x
1  NA
2  NA
3  NA
4  NA
5  NA
6  NA
7  NA
8  NA
9  NA
10 NA

and I have another dataframe as such (the non-sequential row numbers are because this dataframe is a subset of a much larger dataframe):

    x
1  NA
2  4
3  NA
5  NA
6  5
7  71
8  3

What I want to do is to merge the 2 dataframes together the values from b will replace the current values in x for an output like this:

x
1  NA
2  4
3  NA
4  NA
5  NA
6  5
7  71
8  3
9  NA
10 NA

My first instinct is to use a for loop like this:

for (i in rownames(b)){
    a[i,"x"] <- b[i,"x"]
}

However, this is inefficient for large dataframes. I haven't seen an implementation of this using merge and cbind/rbind yet.

Is there a more efficient way to accomplish this?

like image 341
superasiantomtom95 Avatar asked Mar 13 '26 12:03

superasiantomtom95


1 Answers

transform(a, x = b[row.names(a),])
#    x
#1  NA
#2   4
#3  NA
#4  NA
#5  NA
#6   5
#7  71
#8   3
#9  NA
#10 NA
like image 96
d.b Avatar answered Mar 15 '26 03:03

d.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!