执行此read.table时,有几个值无法正确导入:
hs.industry <- read.table("https://download.bls.gov/pub/time.series/hs/hs.industry", header = TRUE, fill = TRUE, sep = "\t", quote = "", stringsAsFactors = FALSE)具体地说,有几个值将industry_code和industry_name连接为industry_code列中的单个值(不确定原因)。假设每个industry_code都是4位数,我的拆分和更正方法是:
for (i in 1:nrow(hs.industry)) {
if (isTRUE(nchar(hs.industry$industry_code[i]) > 4)) {
hs.industry$industry_name[i] <- gsub("[[:digit:]]","",hs.industry$industry_code[i])
hs.industry$industry_code[i] <- gsub("[^0-9]", "",hs.industry$industry_code[i])
}
}我觉得这太棒了,但我不确定哪种方法会更好。
谢谢!
发布于 2017-03-07 02:45:48
问题是,第29行和第30行(如果不计算标题,第28行和第29行)存在格式错误。他们使用4个空格而不是正确的制表符。需要进行一些额外的数据清理。
使用readLines读取原始文本,更正格式错误,然后读取清理后的表格:
# read in each line of the file as a list of character elements
hs.industry <- readLines('https://download.bls.gov/pub/time.series/hs/hs.industry')
# replace any instances of 4 spaces with a tab character
hs.industry <- gsub('\\W{4,}', '\t', hs.industry)
# collapse together the list, with each line separated by a return character (\n)
hs.industry <- paste(hs.industry, collapse = '\n')
# read in the new table
hs.industry <- read.table(text = hs.industry, sep = '\t', header = T, quote = '')发布于 2017-03-07 02:44:10
您不应该遍历每个实例,而是只标识那些有问题的条目,而gsub只标识那些条目:
replace_indx <- which(nchar(hs.industry$industry_code) > 4)
hs.industry$industry_name[replace_indx] <- gsub("\\d+\\s+", "", hs.industry$industry_code[replace_indx])
hs.industry$industry_code[replace_indx] <- gsub("\\D+", "", hs.industry$industry_code[replace_indx])我还使用了"\\d+\\s+"来改进字符串替换,这里我还替换了空格:
gsub("[[:digit:]]","",hs.industry$industry_code[replace_indx])
# [1] " Dimension stone" " Crushed and broken stone"
gsub("\\d+\\s+", "", hs.industry$industry_code[replace_indx])
# [1] "Dimension stone" "Crushed and broken stone"https://stackoverflow.com/questions/42632539
复制相似问题