1

I am using the R programming language (in R Studio). I am trying to import an entire folder of ".txt" files (notepad files) into R and "consistently" name them.

I know how to do this process manually:

#find working directory:

getwd()

[1] "C:/Users/Documents"

#import files manually and name them "consistently":

df_1 <- read.table("3rd_file.txt")
df_2 <- read.table("file_1.txt")
df_3 <- read.table("second_file.txt")

Of course, this will take a long time to do if there are 100 files.

Right now, suppose these files are in a folder : "C:/Users/Documents/files_i_want"

enter image description here

Is there a way to import all these files at once and name them as "df_1", "df_2", "df_3", etc.?

I found another stackoverflow post that talks about a similar problem: How to import folder which contains csv file in R Studio?

setwd("where is your folder")
#
#List file subdirectories
folders<- list.files(path = "C:/Users/Documents/files_i_want")
#
#Get all files...
files <- rep(NA,0)
for(i in c(1:length(folders))) 
{
    files.i <- list.files(path = noquote(paste("C:/Users/Documents/files_i_want/",folders[i], "/", sep = ""))) 
    n <- length(files.i)
    files.i <- paste(folders[i], files.i, sep = "/")
    files <- c(files, files.i)
} 
# 
#
#Read first data file (& add file name as separate column)
T1 <- read.delim(paste("C:/Users/Documents/files_i_want", files[1], sep = ""), sep = "", header=TRUE)
T1 <- cbind(T1, "FileName" = files[1])

But this produces the following error:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :

Is this because there is a problem in the naming convention?

Thanks

stats_noob
  • 5,401
  • 4
  • 27
  • 83

1 Answers1

4

You can try the following :

#Get the path of filenames
filenames <- list.files("C:/Users/Documents/files_i_want", full.names = TRUE)
#Read them in a list
list_data <- lapply(filenames, read.table)
#Name them as per your choice (df_1, df_2 etc)
names(list_data) <- paste('df', seq_along(filenames), sep = '_')
#Create objects in global environment.
list2env(list_data, .GlobalEnv)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thank you @RonakShah! this works perfectly! I just had a question about a warning message that was produced. Is this something to be concerned about? – stats_noob Apr 15 '21 at 03:29
  • Warning messages: 1: In FUN(X[[i]], ...) : incomplete final line found by readTableHeader on 'C:/Users/Documents/files_i_want/3rd_file.txt' 2: In FUN(X[[i]], ...) : incomplete final line found by readTableHeader on 'C:/Users/Documents/files_i_want/file_1.txt' 3: In FUN(X[[i]], ...) : incomplete final line found by readTableHeader on 'C:/Users/Documents/files_i_want/second_file.txt' – stats_noob Apr 15 '21 at 03:29
  • That has to do with the text files and not with the code. Maybe there is an additional new line or space in the text files and usually it is safe to ignore such warnings. – Ronak Shah Apr 15 '21 at 07:08