2

我有一个大文本文件,其中包含来自统一犯罪报告的数据。理想情况下,我想做的只是导入数据并忽略文件中的其他无关内容。实际数据由空格分隔,当数据进入另一个“页面”时,标题信息会重复。我首先尝试使用以下代码导入数据(并且仅导入数据)并手动添加我自己的标题:

  data <- read.fwf("2010SHRall.txt", 
        c(-4,3,8,2,4,5,6,5,4,3,3,4,4,3,3,4,6,5,3,6,26,3),   
        skip=5,       
        col.names=c("AGE","AGENCY","G","MO","HOM","INC","SIT","VA","VS","VR","VE","OA","OS","OR","OE","WEAP","REL","CIR","SUB","AGENCYNAME","STATE"), 
        strip.white=FALSE)

这有效,然后在第 51 行退出。我绝对是一个新手 R 程序员,我尝试用谷歌搜索答案以及搜索 Stack Overflow,但我不知道从这里去哪里。这是我要导入的文本文件的链接。同样,我正在尝试导入数据并删除任何具有标题信息的行或完整数据集不需要的其他部分。

任何人都可以提供的任何帮助将不胜感激。

4

1 回答 1

1

这应该可以工作:

text <- readLines('/tmp/2010SHRall.txt')
group.start <- '^      AGENCY'
group.end <- '(^B)|(^0END OF GROUP)'
data <- character()
inside.group <- FALSE
for (line in text) {
  if (inside.group) {
    if (grepl(group.end, line))
      inside.group <- FALSE
    else
      data <- append(data, line)
  } else if (grepl(group.start, line)) {
    inside.group <- TRUE
  }
}
read.fwf(textConnection(data),
         widths=c(-4,3,8,2,4,5,6,5,4,3,3,4,4,3,3,4,6,5,3,6,26,3),
         header=FALSE,
         col.names=c("AGE","AGENCY","G","MO","HOM","INC","SIT","VA","VS","VR","VE","OA","OS","OR","OE","WEAP","REL","CIR","SUB","AGENCYNAME","STATE"), 
         strip.white=TRUE)

group.start它保留与和group.end正则表达式匹配的行之间的所有行,并丢弃其余行。

于 2012-11-15T00:22:34.827 回答