用R中不同数据帧中具有相同ID的行中的值替换列中的NA

问题描述 投票:0回答:1

我有两个数据框:

    deploy.info <- data.frame(Echo_ID = c("20180918_7.5Fa_1", "20180918_Sebre_3", "20190808_Bake_2", "20190808_NH_2"), 
                      uppermost_bin = c(2, 7, 8, 12))

    spc <- data.frame(species = c("RS", "GS", "YG", "RR", "BR", "GT", "CB"), 
              percent_dist = c(0, 25, 80, 100, 98, 60, 100), 
              percent_dist_from_surf = c(0, 25, 80, 100, 98, 60, 100),
              '20180918_7.5Fa_1' = c(1, 1, 1, "NA", "NA", 1, "NA"),
              '20180918_Sebre_3' = c(1, 2, "NA", "NA", "NA", 4, "NA"), 
              '20190808_Bake_2' = c(1, 3, 7, "NA", "NA", 6, "NA"), 
              '20190808_NH_2' = c(1, 2, 8, "NA", "NA", 6, "NA"))

spc数据框中的最后四列引用我正在deploy.info数据框中处理的每个Echo_ID。我想用每个Echo_ID的uppermost_bin值替换spc数据帧中的NA。有人知道该怎么做吗?

我想要的最终产品看起来像:

    i.want.this <- data.frame(species = c("RS", "GS", "YG", "RR", "BR", "GT", "CB"), 
                      percent_dist = c(0, 25, 80, 100, 98, 60, 100), 
                      percent_dist_from_surf = c(0, 25, 80, 100, 98, 60, 100),
                      '20180918_7.5Fa_1' = c(1, 1, 1, 2, 2, 1, 2),
                      '20180918_Sebre_3' = c(1, 2, 7, 7, 7, 4, 7), 
                      '20190808_Bake_2' = c(1, 3, 7, 8, 8, 6, 8), 
                      '20190808_NH_2' = c(1, 2, 8, 12, 12, 6, 12))

我有超过100列这样的内容,宁愿不参加而必须手动进行此更改。任何想法都将不胜感激。

r rstudio
1个回答
0
投票

我们可以使用Mapreplace通过相应的'uppermost_bin'值将'Echo_ID'列中的NA元素。在OP的数据集中,列为factor,因此已通过type.convert

将其转换为正确的类型
nm1 <- paste0("X", deploy.info$Echo_ID)
spc <- type.convert(spc, as.is = TRUE) 
spc[nm1] <- Map(function(x, y) replace(x, is.na(x), y), 
          spc[nm1], deploy.info$uppermost_bin)
spc
#  species percent_dist percent_dist_from_surf X20180918_7.5Fa_1 X20180918_Sebre_3 X20190808_Bake_2 X20190808_NH_2
#1      RS            0                      0                 1                 1                1              1
#2      GS           25                     25                 1                 2                3              2
#3      YG           80                     80                 1                 7                7              8
#4      RR          100                    100                 2                 7                8             12
#5      BR           98                     98                 2                 7                8             12
#6      GT           60                     60                 1                 4                6              6
#7      CB          100                    100                 2                 7                8             12
© www.soinside.com 2019 - 2024. All rights reserved.