我在目录中有.csv
文件(比如C:/Dowloads
)。我能够使用list.files("path")
读取该目录中的所有文件。但是,我无法使用for
循环读取指定数量的文件。也就是说,假设我有332个文件,我只想读取文件1到10或5到10。
下面是一个示例:
files <- list.files("path")
files ## displays all the files.
现在为了测试,我做了:
k <- files[1:10]
k
## here it displays the files from 1 to 10.
因此,我使用for
循环保留了相同的内容,因为我想逐个读取文件。
for(i in 1:length(k)){
length(i) ## just tested the length
}
但它是以NA
、Null
或1
的方式给予的。
有人能解释我如何使用.csv
循环或其他方式读取指定的for
文件吗?
发布于 2016-07-17 15:45:01
list.files
返回类character
的字符向量。字符向量是字符串(即字符)的向量。函数length
应用于字符向量files
或字符向量files[1:10]
中的元素范围或字符向量files[i]
中的单个元素将分别返回该字符向量中的字符串数、范围内的字符串数或1。相反,使用nchar
获取字符向量的每个元素(每个字符串)的字符数。所以:
path.to.csv <- "/path/to/your/csv/files"
files<-list.files(path.to.csv)
print(files) ## list all files in path
k<-files[1:10]
print(k) ## list first 10 files in path
for(i in 1:length(k)) { ## loop through the first 10 files
print(k[i]) ## each file name
print(nchar(k[i])) ## the number of characters in each file name
df <- read.csv(paste0(path.to.csv,"/",k[i])) ## read each as a csv file
## process each df in turn here
}
注意,在调用paste
时,我们必须对文件名的“路径”进行read.csv
。
编辑:--我想我把它添加到另一种选择:
path.to.csv <- "/path/to/your/csv/files"
files<-list.files(path.to.csv)
for(iFile in files) { ## loop through the files
print(iFile) ## each file name
print(nchar(iFile)) ## the number of characters in each file name
df <- read.csv(paste0(path.to.csv,"/",iFile)) ## read each as a csv file
## process each df in turn here
}
在这里,for
循环位于files
的集合(向量)之上,因此iFile
是i
-th文件名。
希望这能有所帮助。
发布于 2016-07-17 18:25:33
若要一次读取特定数量的文件,可以子集您的文件向量。首先,创建文件的向量,包括路径:
f = list.files("/dir/dir", full.names=T, pattern="csv")
# nb full.names returns the full path to each file
然后,将每个文件读入单独的列表项(在本例中为前10项):
dl = lapply(f[1:10], read.csv)
最后,请看一下列表项目1:
head(dl[[1]])
发布于 2016-07-17 15:44:11
不幸的是,没有可重复的例子可供使用。通常,当我必须做类似的工作时,我会这样做:
files <- list.files(pattern='*.csv') # this search all .csv files in current working directory
for(i in 1:length(files){
read.csv(files[i], stringsAsFactors=F)
}
您的代码无法工作,因为您正在测试索引的长度,而不是向量的长度。希望这能有所帮助
https://stackoverflow.com/questions/38422369
复制相似问题