【问题标题】:extract a column from multiple excel files and concatenate them into a single file with R从多个excel文件中提取一列并用R将它们连接到一个文件中
【发布时间】:2021-05-28 12:31:14
【问题描述】:

我有大约 100 个 excel 文件(一张表),我想提取其中的第 4 列并将它们全部放在 R 中的一个文件中(在这个新文件中,我想将所有列堆叠成一个单列数据,其标题位于第二列)

我怎么能在 R 中做到这一点?提前致谢!


我在这里找到了这个解决方案:(Extracting specific column of different files and put them together in one big file in R)

setwd("XXX")
fileNames <- Sys.glob("*.csv")
extractor <- function(fileName) {
  dataDf <- read.csv2(fileName, header = TRUE) 
  Column4 <- dataDf$Column4
  return(Column4)
}

total.list <- lapply(fileNames, extractor)
total.table <- Reduce(cbind, total.list)
write.table(total.table, file = "New-file.csv")

但我收到此错误消息:结果的行数不是向量长度的倍数 (arg 2) => 因为向量的长度不匹配

我该如何解决这个问题?非常感谢!

【问题讨论】:

    标签: r excel


    【解决方案1】:
    library(tidyverse)
    
    filenames <- list.files(pattern = '\\.xlsx', full.names = TRUE)
    
    map_df(filenames, ~readxl::read_excel(.x) %>% 
              select(4) %>%
              mutate(col = names(.)[1]) %>%
              rename(value = 1)) -> result
    
    writexl::write_xlsx(result, 'new_data.xlsx')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2014-01-21
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多