查看 this NOAA web page 上的“估计全局趋势日值”文件.它是一个 .txt
文件,包含大约 50 个标题行(用前导 #
标识),后跟几千行表格数据。下载文件的链接嵌入在下面的代码中。
我怎样才能读取这个文件,以便最终得到一个包含适当列名和数据的数据框(或 tibble)?
我所知道的所有文本到数据功能都被这些标题行所阻碍。这是我刚刚尝试的,即兴创作 this SO Q&A .我的想法是将文件读入行列表,然后从列表中删除以 #
开头的行,然后是 do.call(rbind, ...)
其余的部分。顶部的下载部分工作正常,但当我运行该函数时,我得到一个空列表。
temp <- paste0(tempfile(), ".txt")
download.file("ftp://aftp.cmdl.noaa.gov/products/trends/co2/co2_trend_gl.txt",
destfile = temp, mode = "wb")
processFile = function(filepath) {
dat_list <- list()
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
append(dat_list, line)
}
close(con)
return(dat_list)
}
dat_list <- processFile(temp)
最佳答案
这里有一个可能的选择
processFile = function(filepath, header=TRUE, ...) {
lines <- readLines(filepath)
comments <- which(grepl("^#", lines))
header_row <- gsub("^#","",lines[tail(comments,1)])
data <- read.table(text=c(header_row, lines[-comments]), header=header, ...)
return(data)
}
processFile(temp)
我们的想法是我们读取所有行,找到以“#”开头的行并忽略它们,除了最后一行将用作标题。我们从 header 中删除“#”(否则它通常被视为注释),然后将其传递给 read.table
以解析数据。
关于r - 如何将结构松散的文本文件中的表格读入 R 中的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042494/