【问题标题】:How to change value in one data frame based on the other data frame?如何根据另一个数据帧更改一个数据帧中的值?
【发布时间】:2019-07-06 22:08:18
【问题描述】:

您好,我需要您的帮助来根据另一个数据框更改一个数据框中的值。例如,有数据框 A 和 B。A 的物种比 B 多,但样本相同。现在我想将数据框 A 中的值更改为: 1) 对于每个样本,不在数据框 B 中或在数据框 B 中的物种()为“否”; 2)数据框B中不是“NA”的物种为“是”。

真实数据有很多种类。

数据框A

       species1 species2    species3    species4    species5    species6
sample1 0.5       0.3          0          0.5          0           0.5
sample2 0.6       0.5          0          0.5          0.5         0
sample3 0.7       0.7          0          0            0           0
sample4 0.8       0.9          0.5        0.5          0           0
sample5 0.9       1.1          0.5        0.3          0           0.5

数据框 B

        species2    species5    species3
sample1   NA          0.3         NA
sample2   NA          0.5         NA
sample3   0.7         NA          0.2
sample4   0.8         0.9         0.5
sample5   NA          NA          0.5

预期结果如下:

       species1 species2    species3    species4    species5    species6
sample1 No        No          No           No          Yes         No
sample2 No        No          No           No          Yes         No
sample3 No        Yes         Yes          No          No          No
sample4 No        Yes         Yes          No          Yes         No
sample5 No        No          Yes          No          No          No

非常感谢。

【问题讨论】:

  • 我还是不明白为什么 Species 3 是 yes yes yes,你是匹配值还是其他一些标准?假设两个数据集中只存在两个值,难道不应该有两个 yes 值吗?
  • 问题已更新。谢谢。

标签: r


【解决方案1】:

使用dplyrbasepurrr

    library(dplyr)
rep_at <- setdiff(names(df1),names(df2))
df1 %>% 
  mutate_at(vars(rep_at),function(x) x="No") -> df1
replacements <- as.data.frame(purrr::map(df2,function(y) 
    ifelse(is.na(y), "no","yes")),
    stringsAsFactors=F)
 df1[,match(names(replacements),names(df1))] <- replacements
  df1

结果:

    species1 species2 species3 species4 species5 species6
1       No       no       no       No      yes       No
2       No       no       no       No      yes       No
3       No      yes      yes       No       no       No
4       No      yes      yes       No      yes       No
5       No       no      yes       No       no       No

【讨论】:

  • 非常感谢。但是,请问为什么mutate_at这一步之后行名变成数字了?
  • 已经好几个小时了,不记得他们变了。您能否详细说明它们是如何变化的?
  • @Bio_farmer 你的意思是sample1、sample2等?
  • 目前无法访问我的电脑。您可以通过将结果篮设置为[] 来解决这个问题,如下所示:stackoverflow.com/questions/40968821/…
  • 非常感谢。所有错误都已解决。两个数据集的名称并不完全一致。再次感谢您。
猜你喜欢
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多