Merging data from different files with same column names

I am trying to merge data from different .txt files (all files in the same directory) where file names are different but each file contains the same column names. Below is the script I am trying to use:

files <- dir("/PATH/")
names <- grep(files, pattern = "AA.*_ss.txt$",value = TRUE)
Data<- map(names, read.delim, stringsAsFactors = FALSE, check.names = FALSE, row.names = NULL)
Merge <- bind_rows(Data) #is it correct?
write.csv(Merge, "./Combined.csv", row.names = F)

I want to insert a column in my combined file where * (it is a number in my file name which is unique for each file) can be listed as a reference to show from which file these rows are taken. Need help with this, please.

Here is an example of extracting the numeric part of two file names and combining the contents of the two files into a data frame.

library(tidyverse)
files <- dir("~/R/Play")
names <- grep(files, pattern = "Dummy",value = TRUE)
names
[1] "Dummy1.csv" "Dummy2.csv"
ExtractedNames <- str_extract(names, "\\d+")
Data<- map(names, read.delim, stringsAsFactors = FALSE, check.names = FALSE, 
            row.names = NULL,sep=",")
Data <- set_names(Data,ExtractedNames)
Merge <- bind_rows(Data,.id = "File") #is it correct?
Merge
  File Name Value
1    1    A    21
2    1    B    42
3    1    C    13
4    1    D   214
5    2    A     2
6    2    B     4
7    2    C     1
8    2    D    21

The code is working fine till ExtractedNames and I can see that the names are extracted from only .txt files. But then the Data command with map function is giving error.

Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
  no lines available in input

I can replicate the error if one of the files is empty. Check the size of the files in the directory and see if the smallest one has any content.

yes, it was the issue. It worked now. thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.