【问题标题】:Data Wrangling in rr中的数据整理
【发布时间】:2021-04-16 00:40:30
【问题描述】:

我正在尝试将我的数据子集到新的数据帧中以执行我的分析。

我有 134 个样本的数据框,其中包含大量信息,但我只对类型、名称和表达式列感兴趣。 如何通过所有这些样本进行循环(或某种迭代方式)以将它们子集到我感兴趣的列中,然后将它们整理到单个数据框中?

我特别想按类型将数据子集到单独的表中(即一个用于蛋白质,一个用于 mRNA)。然后我想将所有样本的蛋白质(或 mRNA)表达包含到一个数据框中。

任何帮助或进一步资源的指导将不胜感激! 谢谢

示例代码

sample1 <- data.frame(type = c("protein", "mRNA"),
                      name = c("DIABLO", "X1345"),
                      expression = c("1.23", "4.265"))

sample2 <- data.frame(type = c("protein", "mRNA"),
                      name = c("DIABLO", "X1345"),
                      expression = c("3.24", "5.33"))

sample3 <- data.frame(type = c("protein", "mRNA"),
                      name = c("DIABLO", "X1345"),
                      expression = c("2.56", "8.11"))

【问题讨论】:

  • 您好,您的帖子中有很多问题。我相信您正在寻找的第一步是samples&lt;-rbind(sample1, sample2, sample3)

标签: r dataframe data-wrangling


【解决方案1】:

将所有数据合并到一个数据帧中,并在type 列上拆分,得到两个单独的数据帧。

library(dplyr)

bind_rows(mget(paste0('sample', 1:3)), .id = 'sample') %>%
  split(.$type) %>%
  list2env(.GlobalEnv)

mRNA

#   sample type  name expression
#2 sample1 mRNA X1345      4.265
#4 sample2 mRNA X1345       5.33
#6 sample3 mRNA X1345       8.11

protein
#   sample    type   name expression
#1 sample1 protein DIABLO       1.23
#3 sample2 protein DIABLO       3.24
#5 sample3 protein DIABLO       2.56

虽然您可能不需要它,但我添加了一个额外的列 (sample) 来识别每行来自哪个数据帧。

【讨论】:

  • 绝妙的方法。
【解决方案2】:

首先将所有数据文件读入list,然后提取部分:

samples <- list(sample1, sample2, sample3)
# Alternate approach
# samples <- lapply(paste0("sample", 1:3), get)
proteins <- do.call(rbind, lapply(samples, function(x) x[1, ]))
proteins
#      type   name expression
# 1 protein DIABLO       1.23
# 2 protein DIABLO       3.24
# 3 protein DIABLO       2.56
mRNAs <- do.call(rbind, lapply(samples, function(x) x[2, ]))
mRNAs
#    type  name expression
# 2  mRNA X1345      4.265
# 21 mRNA X1345       5.33
# 22 mRNA X1345       8.11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多