【问题标题】:Replace values in column using logical vector使用逻辑向量替换列中的值
【发布时间】:2018-11-13 12:36:28
【问题描述】:

我有一个长格式的数据框。 OTU 列有大约 428 个唯一 ID,重复测量导致 26,536 行。

'data.frame':   26536 obs. of  18 variables:
 $ OTU        : chr  "109431" "109431" "109431" "109431" ...
 $ Sample     : chr  "m.ch.45" "m.ch.59" "m.ch.85" "m.ch.51" ...
 $ Abundance  : num  0.994 0.983 0.981 0.975 0.975 ...
 $ X.SampleID : Factor w/ 62 levels "m.ch.1","m.ch.101",..: 28 37 52 33 
                                                8 15 13 7 58 14 ...
 $ Family     : Factor w/ 89 levels 
    "f__","f__[Acidaminobacteraceae]",..: 26 26 26 26 26 26 26 26 26 26 
                                              ...

在 OTU 列中的唯一 ID 中,我想重点关注其中的 9 个(top9names)。 我制作了一个逻辑向量,前 9 名中的所有 OTU 为 TRUE,所有不为 FALSE 的 OTU

matches <- qd_melted$OTU %in% top9names

对于这 9 个 OTU 名称,我想保留相应的家族名称(第 5 列)。对于其他 OTU 名称(~419),我想将 Family 列中的值替换为“Other taxa”。 关于如何编码的任何提示?

【问题讨论】:

    标签: r dataframe replace


    【解决方案1】:

    向因子添加新值时,您需要先更新水平。这是一种方法-

    levels(qd_melted$Family) <- c(levels(qd_melted$Family), "Other taxa")
    
    qd_melted$Family[!matches] <- "Other taxa"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2021-10-01
      相关资源
      最近更新 更多