R:导入文件的整个文件夹 [英] R: Importing Entire Folder of Files

查看:65
本文介绍了R:导入文件的整个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R编程语言(在R Studio中).我正在尝试导入整个文件夹".txt",文件(记事本文件)存入R并一致地"存入R给他们起名字.

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")

当然,如果有100个文件,这将花费很长时间.

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

现在,假设这些文件位于文件夹中:"C:/Users/Documents/files_i_want"

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

是否可以一次导入所有这些文件并将其命名为"df_1","df_2","df_3"等?

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

我发现了另一个谈论类似问题的stackoverflow帖子:

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])

但这会产生以下错误:

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?

谢谢

推荐答案

您可以尝试以下操作:

#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)

这篇关于R:导入文件的整个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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