# 函數(shù)目標:
# 讀取文件中的指定行和指定列
# 不包括注釋行
read_part <- function(file, rows = 1, columns = -1, sep = "\t",
stringsAsFactors = FALSE,
header = FALSE,
check.names = FALSE,
comment.char = "#", ...){
dfl <- list()
if (grepl("gz$", file)){
con <- gzfile(file, open = "rb")
} else{
con <- file(file, open = "r")
}
i <- 0
j <- 1
repeat{
rec <- readLines(con, 1)
if (length(rec) == 0) break
i <- i + 1
# 當rows = -1時, 會讀取所有行
# 超過目標行時停止讀取
if (i > max(rows) & rows != -1) break
# 不考慮注釋行
if (grepl(comment.char, rec )) next
if ( ! i %in% rows & rows != -1) next
items <- strsplit(rec, split = sep, fixed = TRUE)[[1]]
if ( columns == -1){
select_cols <- items
} else{
select_cols <- items[columns]
}
#print(select_cols)
dfl[[j]] <- select_cols
j <- j + 1
}
close(con)
df <- do.call(rbind, dfl)
return(df)
}








暫無數(shù)據(jù)