首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有更有效的拆分列的方法

有没有更有效的拆分列的方法
EN

Stack Overflow用户
提问于 2017-03-07 02:04:13
回答 2查看 67关注 0票数 0

执行此read.table时,有几个值无法正确导入:

代码语言:javascript
复制
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位数,我的拆分和更正方法是:

代码语言:javascript
复制
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])
  }
}

我觉得这太棒了,但我不确定哪种方法会更好。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-07 02:45:48

问题是,第29行和第30行(如果不计算标题,第28行和第29行)存在格式错误。他们使用4个空格而不是正确的制表符。需要进行一些额外的数据清理。

使用readLines读取原始文本,更正格式错误,然后读取清理后的表格:

代码语言:javascript
复制
# 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 = '')
票数 4
EN

Stack Overflow用户

发布于 2017-03-07 02:44:10

您不应该遍历每个实例,而是只标识那些有问题的条目,而gsub只标识那些条目:

代码语言:javascript
复制
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+"来改进字符串替换,这里我还替换了空格:

代码语言:javascript
复制
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"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42632539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档