使用名称序列合并多个csv文件 [英] Merging multiple csv files with name sequence

查看:99
本文介绍了使用名称序列合并多个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中合并700多个csv文件。我能够使用以下代码成功合并它们:

I am trying to merge 700+ csv files in R. I was able to merge them successfully using the code:

library(dplyr)
library(readr)
df <- list.files(full.names = TRUE) %>% 
  lapply(read_csv) %>% 
  bind_rows 

现在,我的问题是文件名另存为flux.0,flux.1,flux。 2 ...... flux.733。 R会按flux.0,flux.1、1.flux.10,flux.100,flux.101 ...的顺序绑定文件。由于文件的顺序对我很重要,因此您可以建议将其合并到上面的代码中吗?
非常感谢您的帮助!

Now my problem is the file names are saved as flux.0, flux.1, flux.2......flux.733. The R binds the files in order of flux.0, flux.1, flux.10, flux.100, flux.101...and so on. Since the sequence of the file is important for me, can you suggest to incorporate this in the above code? Many Thanks for the help!

推荐答案

在这里,您将使用自己的方法得到另一个答案。我刚刚添加了一个读取csv的函数,并添加了一个名为'file'的新列,其文件名不带扩展名。

Here you have another answer using your own approach. I've just added a function that reads the csv and adds a new column called 'file' with the name of the file without the extension.

library(dplyr) 
library(readr) 

df <- list.files(full.names = TRUE) %>% 
    lapply(function(x) {a <- read_csv(x);
                        mutate(a, file = tools::file_path_sans_ext(basename(x)))}) %>%
    bind_rows

这篇关于使用名称序列合并多个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆