阅读固定宽度的文件始终是一个挑战,因为用户需要搞清楚每列的宽度。为了完成这个任务,我使用了readr
中的函数来简化过程。
读取固定宽度文件的主要功能是read_fwf
。另外,还有一个叫fwf_empty
的功能可以帮助用户“猜测”列的宽度。但是这个函数并不总能正确识别列的宽度。这是一个例子。
# Load package
library(readr)
# Read the data
filepath <- "http://ww2.amstat.org/publications/jse/datasets/airport.dat.txt"
# Guess based on position of empty columns
col_pos <- fwf_empty(filepath)
# Read the data
dat <- read_fwf(filepath, col_positions = col_pos)
# Check the data frame
head(dat)
# A tibble: 6 × 6
X1 X2 X3 X4 X5 X6
<chr> <chr> <int> <int> <dbl> <dbl>
1 HARTSFIELD INTL ATLANTA 285693 288803 22665665 165668.76 93039.48
2 BALTO/WASH INTL BALTIMORE 73300 74048 4420425 18041.52 19722.93
3 LOGAN INTL BOSTON 114153 115524 9549585 127815.09 29785.72
4 DOUGLAS MUNI CHARLOTTE 120210 121798 7076954 36242.84 15399.46
5 MIDWAY CHICAGO 64465 66389 3547040 4494.78 4485.58
6 O'HARE INTL CHICAGO 322430 332338 25636383 300463.80 140359.38
的fwf_empty
做了相当不错的工作,以确定除列2和3。它假定它们是来自同一列中的所有列。所以我们需要一些额外的工作。
fwf_empty
的输出是4个元素的列表,显示了标识的开始和结束位置,跳过和列名。我们必须更新开始和结束位置以考虑第2列和第3列的存在。
# Extract the begin position
Begin <- col_pos$begin
# Extract the end position
End <- col_pos$end
# Update the position information
Begin <- c(Begin[1:2], 43, Begin[3:6])
End <- c(End[1], 42, End[2:6])
# Update col_pos
col_pos$begin <- Begin
col_pos$end <- End
col_pos$col_names <- paste0("X", 1:7)
现在我们再次读取数据。
dat2 <- read_fwf(filepath, col_positions = col_pos)
head(dat2)
# A tibble: 6 × 7
X1 X2 X3 X4 X5 X6 X7
<chr> <chr> <int> <int> <int> <dbl> <dbl>
1 HARTSFIELD INTL ATLANTA 285693 288803 22665665 165668.76 93039.48
2 BALTO/WASH INTL BALTIMORE 73300 74048 4420425 18041.52 19722.93
3 LOGAN INTL BOSTON 114153 115524 9549585 127815.09 29785.72
4 DOUGLAS MUNI CHARLOTTE 120210 121798 7076954 36242.84 15399.46
5 MIDWAY CHICAGO 64465 66389 3547040 4494.78 4485.58
6 O'HARE INTL CHICAGO 322430 332338 25636383 300463.80 140359.38
这次read_fwf
函数可以成功读取文件。
来源
2017-04-15 21:12:59
www
你为什么认为你的代码应该工作?该文件当然不是read.table的适当格式。 – Roland
这是一个固定宽度的文件。你必须使用'read.fwf'并指定宽度 –
@Roland,或许它很明显为什么它不起作用,但作为初学者,它不适用于我。我的代码与我链接到的站点中的代码类似,数据文件的格式也相同。因此,我认为它应该工作。 – mahela007