我试图了解如何将 BLS 数据库中的一些文本文件读入 R。
url <- "http://download.bls.gov/pub/time.series/oe/oe.datatype"
datatype <- read.table(url)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :line 1
did not have 6 elements
我也尝试过:
datatype <- read.table(url, header = FALSE)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,
:line 1 did not have 6 elements
还有:
datatype <- read.table(url, sep="\t")
最后一个方法几乎有效,但是当我检查数据框时,看起来第一列已转换为行名称,最后一列填充了 NA。
datatype
datatype_code datatype_name
01 Employment NA
02 Employment percent relative standard error NA
03 Hourly mean wage NA
04 Annual mean wage NA
我还尝试下载并检查该文件,但不确定我在 Notepad++ 中查看的内容。
download.file(url, "datatype.txt")
datatype <- read.table("datatype.txt", sep='\t')
datatype
datatype_code datatype_name
01 Employment NA
02 Employment percent relative standard error NA
03 Hourly mean wage NA
04 Annual mean wage NA
感谢您的任何提示。只是想学习。
最佳答案
正如 @zx8754 所指出的,这个特定文件在每一行中都有一个额外的制表符“\t”,标题行除外。
您可以读取没有标题的文件:
url <- "http://download.bls.gov/pub/time.series/oe/oe.datatype"
df <- read.delim(url, skip = 1, header = FALSE)
head(df)
# V1 V2 V3
# 1 1 Employment NA
# 2 2 Employment percent relative standard error NA
# 3 3 Hourly mean wage NA
# 4 4 Annual mean wage NA
# 5 5 Wage percent relative standard error NA
# 6 6 Hourly 10th percentile wage NA
您还可以单独阅读第一行的标题:
header <- read.delim(url, nrows = 1, header = FALSE, stringsAsFactors = FALSE)
names(df) <- header
head(df)
# datatype_code datatype_name NA
# 1 1 Employment NA
# 2 2 Employment percent relative standard error NA
# 3 3 Hourly mean wage NA
# 4 4 Annual mean wage NA
# 5 5 Wage percent relative standard error NA
# 6 6 Hourly 10th percentile wage NA
此时您可能想要删除第三列:
df <- df[-3]
关于将简单文本文件读入 R - BLS 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504590/