rdplyr

Update values in df from other df sharing same column names


Let's say I have two separate data frames. I want to keep the df_old, but I want to replace the values (with shared column names) with the values from the df_new. How would I do that?

So "other" in df_old would maintain values but values from other column names would update with the df_new values. Also worth stating that these two data frames could contain one hundred or more column names.

avg_sleep <- c(21, 18, 17, 10)
rating <- 1:4
other <- 5:8
df_old = data.frame(rating, avg_sleep, other)

avg_sleep <- c(16,15,18,19)
rating <- 2:5
df_new = data.frame(rating, avg_sleep)


Solution

  • You can overwrite the columns, using the new column names a reference:

    df_old[names(df_new)] <- df_new
    
      rating avg_sleep other
    1      2        16     5
    2      3        15     6
    3      4        18     7
    4      5        19     8