【问题标题】:Combining multiple files containing only one number合并仅包含一个数字的多个文件
【发布时间】:2021-11-06 18:30:56
【问题描述】:

我有一个只包含一个数字的文件列表。我想将所有文件合并到一个数据框中,其中一列包含文件名,一列包含该文件的相应编号。我尝试了以下方法,但读取文件失败。

有效的单个文件示例:

> read.csv(file="file1.stats",check.names = F)
[1] 2659344201
<0 rows> (or 0-length row.names)


> read.csv(file="file2.stats",check.names = F)
[1] 92424242
<0 rows> (or 0-length row.names)

合并不起作用:

file_list = list.files(pattern=".stats")    
datalist = lapply(file_list, function(x){
  dat = read.csv(file=x,check.names = F)
})

read.table 中的错误(file = file,header = header,sep = sep,quote = quote,: 输入中没有可用的行

 joined <- join_all(dfs = datalist,by = "V1",type ="full" )  

【问题讨论】:

    标签: r


    【解决方案1】:

    以下应该可以工作,虽然没有测试,因为我没有你的文件。

    library(data.table)
    file_list = list.files(pattern=".stats")  
    data_table = rbindlist(lapply(file_list, function(x){
      fread(file=x)
    }))
    

    rbindlist 将简化您的列表,而无需经历加入的麻烦。

    【讨论】:

    • 如果回答对您解决问题有帮助,您可以接受。
    【解决方案2】:

    基于purrr::map_dfr的解决方案:

    library(tidyverse)
    
    # create 10 csv files in the /tmp directory
    walk(1:10, ~ write(sample(1111111:9999999,1), paste0("/tmp/file",.x,".csv")))
    
    # gets the names of the files
    files <- dir("/tmp/","*.csv")
    
    map_dfr(files, ~ data.frame(fname = .x, read.csv(paste0("/tmp/",.x), header = F)))
    
    #>         fname      V1
    #> 1   file1.csv 6803283
    #> 2  file10.csv 4835472
    #> 3   file2.csv 2645034
    #> 4   file3.csv 9766210
    #> 5   file4.csv 8570853
    #> 6   file5.csv 7384528
    #> 7   file6.csv 7609801
    #> 8   file7.csv 1244294
    #> 9   file8.csv 5098257
    #> 10  file9.csv 4940697
    

    或者,使用dplyr:

    library(tidyverse)
    
    # create 10 csv files in the /tmp directory
    walk(1:10, ~ write(sample(1111111:9999999,1), paste0("/tmp/file",.x,".csv")))
    
    # gets the names of the files
    files <- dir("/tmp/","*.csv")
    
    files %>% 
      data.frame %>%  setNames("fnames") %>% 
      rowwise() %>% mutate(read.csv(paste0("/tmp/",fnames), header = F))
    
    #> # A tibble: 10 × 2
    #> # Rowwise: 
    #>    fnames          V1
    #>    <chr>        <int>
    #>  1 file1.csv  3484087
    #>  2 file10.csv 9333635
    #>  3 file2.csv  1455252
    #>  4 file3.csv  9665802
    #>  5 file4.csv  8401813
    #>  6 file5.csv  5864912
    #>  7 file6.csv  9494831
    #>  8 file7.csv  5230778
    #>  9 file8.csv  9717400
    #> 10 file9.csv  9761327
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2013-01-23
      • 2011-06-14
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      相关资源
      最近更新 更多