Skip to content

replacing values of rows with identical row names in two dataframes

1 message · Jeff Newmiller

#
Please use reply-all to keep the mailing list in the loop,  and use plain text rather than HTML to make sure the your message gets through uncorrupted. 

?merge
?lapply

# untested
# align rows by date
df1a <- merge( df1, df2, by="date", all.x=TRUE )
# like-named columns have .x or .y appended
df1an0  <- grep( "\\.x$", names( df1a ), values=TRUE )
df1an <- substr( df1an0, 1, nchar( df1an0 ) - 2 )
# make a list of updated columns
df1b <- lapply( df1an, function(nm) { 
   nmx  <- paste0( nm, ".x" )
   nmy  <- paste0( nm, ".y" )
   ifelse( is.na( df1a[[ nmx ]] ), df1a[[ nmy ]], df1a[[ nmx ]] )
 }
# set the names of the fixed columns
df1b <- setNames( df1b, df1an )
# figure out the names of the non-duped columns
df1an1 <- grep( "\\.[xy]$", names( df1a ), invert =TRUE )
# make a new data frame
df1c  <- data.frame( df1a[ , df1an1, drop=FALSE ], df1b )