Search code examples
rdataframereplacer-rownames

R - replace specific values in df with values from other df by matching row names


I have df1:

df1 <- data.frame(X1 = c(2,5,1,5,4,6),
              X2 = c(1,4,2,5,2,9),
              X3 = c(8,4,2,6,3,8))
rownames(df1) <- rownames(df1) <- c("a","b","c","d","e","f")
  X1 X2 X3
a  2  1  8
b  5  4  4
c  1  2  2
d  5  5  6
e  4  2  3
f  6  9  8

and df2:

df2 <- data.frame(X1 = c(9,8,0),
              X2 = c(4,6,2),
              X3 = c(7,0,2)
rownames(df2) <- c("b","c","f")
  X1 X2 X3
b  9  4  7
c  8  6  0
f  0  2  2

my goal is to update only the values in df1 with values of df2 where their rownames are identical:

  X1 X2 X3
a  2  1  8
b  9  4  7
c  8  6  0
d  5  5  6
e  4  2  3
f  0  2  2

I feel this should be rather simple but I could not find an answer in the forum nor figure this out by myself.

Note: all rows of df2 are present in df1


Solution

  • Another dplyr option with rows_update:

    df1 <- data.frame(X1 = c(2,5,1,5,4,6),
                      X2 = c(1,4,2,5,2,9),
                      X3 = c(8,4,2,6,3,8))
    rownames(df1) <- rownames(df1) <- c("a","b","c","d","e","f")
    
    df2 <- data.frame(X1 = c(9,8,0),
                      X2 = c(4,6,2),
                      X3 = c(7,0,2))
    rownames(df2) <- c("b","c","f")
    
    library(dplyr)
    library(tibble)
    df1 %>%
      rownames_to_column() %>%
      rows_update(df2 %>% rownames_to_column(), by = "rowname") %>%
      column_to_rownames()
    #>   X1 X2 X3
    #> a  2  1  8
    #> b  9  4  7
    #> c  8  6  0
    #> d  5  5  6
    #> e  4  2  3
    #> f  0  2  2
    

    Created on 2022-07-19 by the reprex package (v2.0.1)