【问题标题】:R loop for showing top most abundant rows in multiple data framesR循环用于显示多个数据帧中最丰富的行
【发布时间】:2021-06-20 01:31:41
【问题描述】:

我有 52 个数据文件,每个文件包含两列:蛋白质和丰度。 蛋白质列有一个蛋白质名称,丰度列包含一个数字,显示样品中有多少蛋白质。每个文件中有数千种蛋白质,它们没有按丰度的顺序排列。

例子:

样本 1

protein abundance
x 500
y 300
z 400

样本 2

protein abundance
x 300
y 800
z 200

我想在 R 中编写一个循环来遍历所有 52 个文件,并从每个文件中选择前 2 个最丰富的蛋白质,然后制作一个有 4 列的新数据框(前两个包含两个最丰富的蛋白质的名称,后两个包含这两种蛋白质的丰度值)和 52 行(每个数据文件一行)。

most abundant protein second most abundant protein abundance for MAP abundance for SMAP
sample1 protein x protein z 500 400
sample2 protein y protein x 800 300
etc

到目前为止,我有以下内容:

filelist<- list.files(pattern = ".csv") 

dataabund<-''

for(i in 1:length(filelist)){
  data <- read.table(filelist[i], header = T) 
  dataabund [i] <- head(arrange(data, desc(data$abundance)), n = 2)
  }

mostabund <-  data.frame(filelist, dataabund)

但是,这会创建一个奇怪的数据框,它不会显示丰富度。

任何帮助将不胜感激!

【问题讨论】:

    标签: r dataframe loops


    【解决方案1】:

    你可以试试这个方法-

    library(tidyverse)
    
    filelist<- list.files(pattern = ".csv") 
    
    result <- map_df(filelist,~ {
      read.table(x, header = T) %>%
        slice_max(abundance, n = 2, with_ties = FALSE) %>%
        mutate(col = c('first', 'second')) %>%
        pivot_wider(names_from = col, values_from = c(protein, abundance))
    })
    
    result
    

    【讨论】:

    • 谢谢罗纳克!当我运行它时,我得到 Error: unexpected '}' in "}" 我不知道为什么
    • 是的,有一个错字。尝试更新的答案@LoayJabre
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多