Dir*_*tel 25
快速草案,未经测试:
使用list.files()aka dir()动态生成文件列表.
这将返回一个向量,只是在for循环中沿向量运行.
读取第i个文件,然后使用assign()将内容放入新变量file_i
这应该为你做的伎俩.
Fre*_*red 24
谢谢大家的回复.
为了完整性,这里是我加载任意数量(制表符)分隔文件的最终答案,在这种情况下有6列数据,其中第1列是字符,2是因子,余数是数字:
##Read files named xyz1111.csv, xyz2222.csv, etc.
filenames <- list.files(path="../Data/original_data",
pattern="xyz+.*csv")
##Create list of data frame names without the ".csv" part
names <-substr(filenames,1,7)
###Load all files
for(i in names){
filepath <- file.path("../Data/original_data/",paste(i,".csv",sep=""))
assign(i, read.delim(filepath,
colClasses=c("character","factor",rep("numeric",4)),
sep = "\t"))
}
Run Code Online (Sandbox Code Playgroud)
Hon*_*Ooi 14
assign与包含所需数据框名称的字符变量一起使用.
for(i in 1:100)
{
oname = paste("file", i, sep="")
assign(oname, read.csv(paste(oname, ".txt", sep="")))
}
Run Code Online (Sandbox Code Playgroud)
这是一种使用lapply解压缩data.frames列表的方法
filenames <- list.files(path="../Data/original_data",
pattern="xyz+.*csv")
filelist <- lappy(filenames, read.csv)
#if necessary, assign names to data.frames
names(filelist) <- c("one","two","three")
#note the invisible function keeps lapply from spitting out the data.frames to the console
invisible(lapply(names(filelist), function(x) assign(x,filelist[[x]],envir=.GlobalEnv)))
Run Code Online (Sandbox Code Playgroud)
这个答案是对哈德利答案的一个更有用的补充.
虽然OP特别希望每个文件作为一个单独的对象读入他们的R工作区,但许多其他人天真地登陆这个问题可能会认为这就是他们想要做的事情,而实际上他们最好将文件读入一个数据框列表.
所以对于记录,这里是你如何做到这一点.
#If the path is different than your working directory
# you'll need to set full.names = TRUE to get the full
# paths.
my_files <- list.files("path/to/files")
#Further arguments to read.csv can be passed in ...
all_csv <- lapply(my_files,read.csv,...)
#Set the name of each list element to its
# respective file name. Note full.names = FALSE to
# get only the file names, not the full path.
names(all_csv) <- gsub(".csv","",
list.files("path/to/files",full.names = FALSE),
fixed = TRUE)
Run Code Online (Sandbox Code Playgroud)
现在可以引用任何文件my_files[["filename"]],实际上只是在工作区中有单独的变量并没有太糟糕filename,而且通常更方便.
从文件夹中读取所有 CSV 文件并创建与文件名相同的向量:
setwd("your path to folder where CSVs are")
filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))
for(i in filenames){
assign(i, read.csv(paste(i, ".csv", sep="")))
}
Run Code Online (Sandbox Code Playgroud)