R -通过匹配行名称将df中的特定值替换为其他df中的值

eaf3rand  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(141)

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

和DF2:
一个二个一个一个
我的目标是仅用行名称相同的df2的值更新df1中的值:

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

我觉得这应该很简单,但我在论坛上找不到答案,也没有自己弄清楚。
注意:df2的所有行都存在于df1中

k97glaaz

k97glaaz1#

试试看

df1[na.omit(match(rownames(df1), rownames(df2))),] <- df2

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

jfgube3f2#

rows_update的另一个dplyr选项:

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

reprex package(v2.0.1)于2022年7月19日创建

nwnhqdif

nwnhqdif3#

另一种可能的解决方案:

library(tidyverse)
             
bind_rows(df1 %>% rownames_to_column(), df2 %>% rownames_to_column()) %>% 
  group_by(rowname) %>% 
  slice_tail(n = 1) %>% 
  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

相关问题