【问题标题】:join data frames for specific column连接特定列的数据框
【发布时间】:2021-10-22 19:25:04
【问题描述】:

我有几个格式如下的数据框。我想通过species 加入/合并数据帧并从所有数据帧中提取kmers,以便输出包含species 的一列和kmers 的多列,每个文件一个形式。然后,kmers 列将给出它所源自的文件的名称。 df1

reads taxReads kmers species
232 2323 23234 Bacteria
555 12 4545 Virus

df2

reads taxReads kmers species
12 23 56 Bacteria
932 1213 12 Virus

出来

species df1 df2
Bacteria 23234 56
Virus 4545 12

我尝试使用 join_all 制作脚本,但它没有选择正确的列 (kmers):

file_list = list.files(pattern="tsv$")    

datalist = lapply(file_list, function(x){
  dat = read.csv(file=x, header=T, sep = "\t")
  names(dat)[2] = x
  return(dat)
})
joined <- join_all(dfs = datalist,by = "species",type ="full" )  

【问题讨论】:

    标签: r join


    【解决方案1】:

    我假设您已将文件读入list of frames,以文件的基本名称命名(已删除扩展名)。将帧列表命名为dfs,我们有

    dfs <- list(df1 = structure(list(reads = c(232L, 555L), taxReads = c(2323L, 12L), kmers = c(23234L, 4545L), species = c("Bacteria", "Virus")), class = "data.frame", row.names = c(NA, -2L)), df2 = structure(list(reads = c(12L, 932L), taxReads = c(23L, 1213L), kmers = c(56L,12L), species = c("Bacteria", "Virus")), class = "data.frame", row.names = c(NA, -2L)))
    
    dfs
    # $df1
    #   reads taxReads kmers  species
    # 1   232     2323 23234 Bacteria
    # 2   555       12  4545    Virus
    # $df2
    #   reads taxReads kmers  species
    # 1    12       23    56 Bacteria
    # 2   932     1213    12    Virus
    

    从这里开始,分两步:

    1. kmers 列重命名为文件名(无扩展名),并过滤掉不需要的列,

      dfs <- Map(function(x, nm) { names(x)[names(x) == "kmers"] <- nm; x[, c("species", nm)]; }, dfs, names(dfs))
      dfs
      # $df1
      #    species   df1
      # 1 Bacteria 23234
      # 2    Virus  4545
      # $df2
      #    species df2
      # 1 Bacteria  56
      # 2    Virus  12
      
    2. 使用merge 减少。

      Reduce(function(d1, d2) merge(d1, d2, by = "species", all = TRUE), dfs)
      #    species   df1 df2
      # 1 Bacteria 23234  56
      # 2    Virus  4545  12
      

      这可以在 here 使用 Reduce(merge, dfs) 进行编码,但我使用两个参数的 anon-func 打破了它,以便您可以控制 merge 的一些选项。

    【讨论】:

    • 我收到关于零长度输入的错误,但是,我的所有文件都应包含行:mapply 中的错误(FUN = f,...,SIMPLIFY = FALSE):不能混合零长度输入与那些非零长度
    • 当我没有您的数据时,很难解决类似的问题。读入后开始查看每一帧,例如all(sapply(dfs, function(z) c("kmers","species") %in% names(z)))
    • > all(sapply(datalist, function(z) c("kmers","species") %in% names(z))) [1] TRUE
    • 我的数据帧在读取所有数据帧的数据列表中表示为 [[1]] 和 [[2]](在您的示例中为 dfs)
    • 也许是names(dfs) &lt;- tools::file_path_sans_ext(basename(file_list))?
    猜你喜欢
    • 2011-09-12
    • 2018-04-30
    • 1970-01-01
    • 2020-04-08
    • 2015-08-15
    • 1970-01-01
    • 2015-04-28
    • 2018-12-10
    相关资源
    最近更新 更多