Merge data frames and overwrite values
merge, r
Solution
merdat <- merge(dfrm1,dfrm2, by="Date") # seems self-documenting
# explanation for next line in text below.
merdat$Col2.y[ is.na(merdat$Col2.y) ] <- merdat$Col2.x[ is.na(merdat$Col2.y) ]
Then just rename 'merdat$Col2.y' to 'merdat$Col2' and drop 'merdat$Col2.x'.
In reply to request for more comments: One way to update only sections of a vector is to construct a logical vector for indexing and apply it using "[" to both sides of an assignment. Another way is to devise a logical vector that is only on the LHS of an assignment but then make a vector using `rep()` that has the same length as `sum(logical.vector)`. The goal is both instances is to have the same length (and order) for assignment as the items being replaced.
Problem
How do I merge 2 similar data frames but have one with greater importance? For example: Dataframe 1 ``` Date Col1 Col2 jan 2 1 feb 4 2 march 6 3 april 8 NA ``` Dataframe 2 ``` Date Col2 Col3 jan 9 10 feb 8 20 march 7 30 april 6 40 ``` merge these by Date with dataframe 1 taking precedence but dataframe 2 filling blanks DataframeMerge ``` Date Col1 Col2 Col3 jan 2 1 10 feb 4 2 20 march 6 3 30 april 8 6 40 ``` EDIT - SOLUTION ``` commonNames <- names(df1)[which(colnames(df1) %in% colnames(df2))] commonNames <- commonNames[commonNames != "key"] dfmerge<- merge(df1,df2,by="key",all=T) for(i in commonNames){ left <- paste(i, ".x", sep="") right <- paste(i, ".y", sep="") dfmerge[is.na(dfmerge[left]),left] <- dfmerge[is.na(dfmerge[left]),right] dfmerge[right]<- NULL colnames(dfmerge)[colnames(dfmerge) == left] <- i } ```