要为lapply 添加一个计数器,我会这样做:
file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
idx=1:length(filenames) #this will server as your 'counter'
lapply(idx, function(i) {print(file_names[i]); read.csv(file=file_names[i],header = FALSE)}) # this will print the file and when the loop stops you'll see the file that is faulty
但是,作为另一种解决方案 - 既要知道哪些文件有问题并自然地跳过它们 - 我会这样做:
wanted=c()
for(f in file_names){
first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line > quota)){ #set quota to provide threshold for a number of columns
wanted=c(wanted,f)
}
}
您也可以使用sapply 执行上述操作。
然后:
all_dta <- do.call(rbind, lapply(wanted, function(x) read.csv(file=x,header = FALSE)))
如果您想知道哪些文件有问题(即哪些文件不包含足够的列)。只需找到列数少于配额的文件即可:
unwanted=c()
for(f in file_names){
first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line < quota)){
unwanted=c(unwanted,f)
}
}