我正在尝试读取一个文本文件(https://www.bls.gov/bdm/us_age_naics_00_table5.txt)到R
中,但我不知道如何解析它。正如你所看到的,列名(年份(并不都位于同一行,数据之间的空间也不一致。我熟悉使用read.csv()
和read.delim()
,但我不知道如何读取像这样的复杂文件。
下面是一个手动解析:
require(readr)
string = read_lines(file="https://www.bls.gov/bdm/us_age_naics_00_table5.txt")
string = string[nchar(string) != 0]
string = string[-c(1,2)] # don't contain information
string = string[string != " "]
string = string[-151] # footnote
sMatrix = matrix(string, nrow = 30)
dfList = sapply(1:ncol(sMatrix), function(x) readr::read_table(paste(sMatrix[,x])))
df = do.call(cbind,dfList)
df = df[,!duplicated(colnames(df))] # removes columns with duplicate names
如果你想重新编码"_"作为NA
,并格式化数字:
df[df == "_"] = NA
df = as.data.frame(sapply(df, function(x) gsub(",","",x)))
i <- apply(df, 2, function(x) !any(is.na(as.numeric(na.omit(x))))) # if a column can be converted to numeric without any NAs, e.g. column 1 can't
df[,i] = lapply(df[,i], as.numeric)