根据另一个数据框填充数据框中的NA值。

4

我有两个数据框架,它们几乎具有相同的样本。 df1 有许多样本,它包含几乎所有在df2中找到的样本,除了2或3个样本之外。

df1中,有一列,比如说性别,其中有NA值。这些性别值在df2中被找到。

我想要根据df2为每个样本在df1中填充NA值,对于它们之间共享的样本。

我该怎么做?特别是df1df2大得多,而且样本不按相同顺序排列。

例如,假设这是df1:

       samples       gender
1        Pt8           NA
2        Pt102         NA
3        Pt87          NA
4        Pt1           NA

这是 df2:

      subject_id     gender
1        Pt1          male
2        Pt102        male
3        Pt6          female
4        Pt8          male

所以我只需根据样本名称填写df1中的NA值。

2个回答

1

我们可以使用连接操作

library(data.table)
setDT(df1)[df2, gender := fcoalesce(as.character(gender), i.gender), 
   on= .(samples = subject_id)]

1

更新:请查看评论(已删除错误的第一个答案):

library(dplyr)

bind_rows(df1, df2 %>% 
            rename_with(~colnames(df1))) %>% 
  arrange(gender) %>% 
  distinct(samples, .keep_all = TRUE) %>% 
  semi_join(df1, by="samples") %>% 
  mutate(samples = factor(samples, levels = df1$samples)) %>%
  arrange(samples)

  samples gender
4     Pt8   male
2   Pt102   male
3    Pt87   <NA>
1     Pt1   male

2
但是 Pt1Pt8 呢?它们在两个数据框中都有出现,只是顺序不同。 - Programming Noob
感谢您的反馈。很抱歉一开始没有理解清楚。这是更新版本。 - TarJae

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接