나는 두 가지 기능을 통해 원하는 것을 할 수 있다고 생각합니다.
먼저 두 번째 줄이 공백 인 파일을 확인하는 기능입니다.
second_blank <- function(path = ".", pattern = "\\.csv"){
fls <- list.files(path = path, pattern = pattern)
second <- sapply(fls, function(f) readLines(f, n = 2)[2])
which(nchar(gsub(",", "", second)) == 0)
}
그런 다음 해당 줄이있는 파일을 한 번에 하나씩 읽는 기능. 첫 번째 줄은 열 머리글이고 적어도 두 번째 줄은 비어 있다고 가정합니다. 도트 인수 ...
이 있으며 다른 인수를 read.table
에 전달할 수 있습니다 (예 : stringsAsFactors = FALSE
).
skip_blank <- function(file, ...){
header <- readLines(file, n = 1)
header <- strsplit(header, ",")[[1]]
count <- 1L
while(TRUE){
txt <- scan(file, what = "character", skip = count, nlines = 1)
if(nchar(gsub(",", "", txt)) > 0) break
count <- count + 1L
}
dat <- read.table(file, skip = count, header = TRUE, sep = ",", dec = ".", fill = TRUE, ...)
names(dat) <- header
dat
}
이제 예제 사용법.
second_blank(pattern = "csv") # a first run as an example usage
inx <- second_blank() # this will be needed later
fl_names <- list.files(pattern = "\\.csv") # get all the CSV files
df_list <- lapply(fl_names[inx], skip_blank) # read the problem ones
names(df_list) <- fl_names[inx] # tidy up the result list
df_list
지금까지 해보신 것은 무엇입니까? [좋은 질문을하는 법] (http://stackoverflow.com/help/how-to-ask) 및 [재현 가능한 예] (http://stackoverflow.com/questions/)에 대한 정보를 읽어보십시오. 5963269/how-to-make-a-great-r-reproducible-example/5963610 참조). 이렇게하면 다른 사람들이 당신을 도울 수있게됩니다. – Jaap
각 파일을'read.csv'로 읽는 대신'readLines'를 사용하여 10 줄을 읽으십시오. 몇 줄의 빈 줄이 있는지 계산하고'read.csv'를 사용하여 적절한 줄 수. –
@AndrewGustar의 의견을 보았습니다. 이것이 바로 아래의 코드입니다. –