【问题标题】:aggregate columns with 2 data frames用 2 个数据框聚合列
【发布时间】:2021-04-08 13:22:14
【问题描述】:

我正在尝试使用 R(data.table?)在特定条件下聚合多个列... 我有一个数据框 df1,其列 12:262 包含每个样本(行)的物种丰度(每列)

sample species1  species2
sample1    1    21
sample2   47    36
sample3    8    32

在另一个数据框 df2 中,我有每个物种(行)的门、属等。

species phylum  genus
species1    X    A
species2    Y    B

我想汇总 df1 中物种属于同一门的所有列(在 df2 中定义)... 这有意义吗?

谢谢!

【问题讨论】:

  • 您能否根据您的示例阐明最终输出的外观?例如,您是否想要每个phylum 的所有物种/样本的总数/丰度?此外,您提到 data.table 时带有问号,并带有标签 - 您更喜欢 data.table 解决方案吗?

标签: r data.table


【解决方案1】:

data.table 版本

library(data.table)
dt1 <- data.table(
  sample = c("sample1", "sample2", "sample3"),
  species1 = c(1, 47, 8),
  species2 = c(21, 36, 32))

dt2 <- data.table(
  species = c("species1", "species2"),
  phylum = c("X", "Y"),
  genus = c("A", "B")
)

# long format 
dt1_long <-
  melt(
    dt1,
    id.vars = 'sample',
    variable.name = "species",
    value.name = "abundence"
  )
# join and group
dt1_long[dt2,on = "species",by = "phylum"]

【讨论】:

    【解决方案2】:

    首先要做的是重塑df1。如果将数据从“宽”格式转换为“长”格式,每个样本将有多行。然后,您可以将其与 species 变量的第二个数据集合并。从这里开始,您还没有详细说明您希望如何聚合数据,但我提供了两个简单的示例。您应该能够轻松地调整聚合代码以包含您需要的任何内容。

    library(tidyr)
    library(dplyr)
    
    df1 <- data.frame(
      sample = c("sample1", "sample2", "sample3"),
      species1 = c(1, 47, 8),
      species2 = c(21, 36, 32))
    
    df2 <- data.frame(
      species = c("species1", "species2"),
      phylum = c("X", "Y"),
      genus = c("A", "B")
    )
    
    df1_long <- tidyr::pivot_longer(df1, starts_with("species"),
                                    names_to = "species", values_to = "abundance")
    
    df3 <- dplyr::left_join(df1_long, df2, by = "species")
    
    df3 %>% 
      group_by(phylum) %>% 
      summarize(total_abundance = sum(abundance), 
                avg_abundance = mean(abundance))
    

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多