【问题标题】:Calculate relative abundance by row label in R? (vegan package?)通过R中的行标签计算相对丰度? (素食套餐?)
【发布时间】:2016-05-06 21:21:23
【问题描述】:

我正在尝试根据行标签或名称计算相对丰度(获取 df$path1 中每个测试的相对丰度。所以我想计算来自 test1 的计数的相对丰度,并计算相对丰度分别来自test2 的计数丰度。来自test1 的相对丰度数之和等于1。

我目前正在使用vegan 包,但可以使用其他选项。

测试数据集:

library(vegan)
df <- data.frame(x = c("a", "b", "c", "d", "e"), 
                 path1 = c("test1", "test1", "test2", "test2", "test3"),
                 value = c(40, 10, 34, 12, 20))
df$relabun <- decostand(df[3], 2, method = "total") #takes relative abundace of whole column

基于df$path1 的相对丰度的理想输出如下所示:

x path1 relabun_bypath1
a test1 0.8
b test1 0.2
c test2 0.74
d test2 0.26
e test3 1

【问题讨论】:

    标签: r dataframe vegan


    【解决方案1】:

    这是一个经典的拆分-应用-组合问题。基础 R 中最直接的方式是

    • split按组分割data.frame,
    • 使用*apply 应用函数,然后
    • do.call(rbind, ... )unlist 结合使用。

    所以

    unlist(lapply(split(df, df$path1), function(x){x$value / sum(x$value)}))
    #    test11    test12    test21    test22     test3 
    # 0.8000000 0.2000000 0.7391304 0.2608696 1.0000000 
    

    我们可以将其分配给一个新变量。但是,base 有一个很好的函数,虽然名字有点奇怪,叫做 ave,它可以为我们跨组应用函数:

    ave(df$value, df$path1, FUN = function(x){x / sum(x)})
    # [1] 0.8000000 0.2000000 0.7391304 0.2608696 1.0000000
    

    这样更简洁,同样可以分配给一个新变量。

    如果您更喜欢 Hadleyverse,dplyr 的分组可以使过程更具可读性:

    library(dplyr)
    df %>% group_by(path1) %>% mutate(relAbundByPath = value / sum(value))
    # Source: local data frame [5 x 4]
    # Groups: path1 [3]
    # 
    #        x  path1 value relAbundByPath
    #   (fctr) (fctr) (dbl)          (dbl)
    # 1      a  test1    40      0.8000000
    # 2      b  test1    10      0.2000000
    # 3      c  test2    34      0.7391304
    # 4      d  test2    12      0.2608696
    # 5      e  test3    20      1.0000000
    

    如您所见,它返回一个新版本的 data.frame,我们可以用它来覆盖现有的或制作一个新副本。

    无论您选择哪种路线,都要对逻辑感到满意,因为您可能会经常使用它。更好的是,全部学习。还有tapplymapply/Map。还有data.table...为什么不呢?


    注意:如果您愿意,也可以将 value / sum(value)) 构造替换为 prop.table 函数。它更简洁(例如ave(df$value, df$path1, FUN = prop.table)),但它的作用不太明显,这就是我在这里没有使用它的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多