【问题标题】:Combining multiple .csv files using row.names使用 row.names 组合多个 .csv 文件
【发布时间】:2021-10-09 02:41:00
【问题描述】:

我有多个 .csv 文件(目前为 4 个,但将来会有所变化),我正在尝试将它们导入 R 中(导入单个数据框)。

我提取了文件名并在 lapply 中使用它来将它们加载为列表列表并定义行名。每个文件都有一个行名列和一个包含数据的列,如下所示:

每个单独的文件

lapply 后 R 中的列表列表

count_files <- list.files()
count_lists <- lapply(count_files, read.csv, sep=",", header=TRUE, row.names="ENSG")

我需要的是 R 中的最终数据框看起来像:

R 中的最终数据帧

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以尝试在Reduce 中使用merge 并按行名加入数据帧。

    result <- Reduce(function(x, y) merge(x, y, by = 'row.names', all = TRUE), count_lists)
    result[is.na(result)] <- 0
    result
    

    【讨论】:

      【解决方案2】:

      我们可以在tidyverse 这样做

      library(dplyr)
      library(purrr)
      map(count_lists, ~ .x %>%
                       rownames_to_column('rn')) %>%
           reduce(full_join, by = 'rn') %>%
           mutate(across(everything(), replace_na, 0))
      

      【讨论】:

        猜你喜欢
        • 2020-06-08
        • 1970-01-01
        • 2012-12-08
        • 2013-08-02
        • 2013-02-11
        • 2011-04-06
        • 2015-06-19
        • 2018-02-14
        • 1970-01-01
        相关资源
        最近更新 更多