我正在尝试将csv文件导入R,其中行的格式如下:
012002001 14.852DL 0000000034630100304660
012002001 84.031GG 0000001049180100304660
012002001 84.033DO 0000001297780100304660
012002001 84.042GG 0000000780000100304660
不幸的是,空格与字段不对应。字段说明如下。
Field Data Element Positions Length
1 GU Code - State 1-2 2
GU Code - Type 3 1
GU Code - County 4-6 3
GU Code - Place 7-9 3
GU Code - Split 10-12 3
2 Program ID Code 13-18 6
3 Object Code 19-20 2
4 Funding Sign 21 1
5 Funding Amount 22-33 12
6 FIPS Code - State 34-35 2
FIPS Code - County 36-38 3
FIPS Code - Place 39-43 5
Pass-Through Flag 44 1
7 Agency Code 45-48 4
如何以正确表示变量的方式将此文件导入R?
谢谢!
答案 0 :(得分:6)
这不是CSV文件。 CSV是一个“逗号分隔值”文件。您要处理的是固定宽度的文件格式。请参阅此处提供的答案:Read fixed width text file
library(readr)
x <- read_fwf(
file="http://www.cpc.ncep.noaa.gov/data/indices/wksst8110.for",
skip=4,
fwf_widths(c(12, 7, 4, 9, 4, 9, 4, 9, 4)))
答案 1 :(得分:0)
或者,这是在基数R中执行此操作的另一种方法。为每个变量定义起始位置:
test <- c("012002001 14.852DL 0000000034630100304660 ")
start.pos <- c(1,3,4,7,10,13,19,21,22,34,36,39,44,45)
end.pos <- lead(start.pos)-1
z <- 0
为每个start.pos
取子字符串:
for (i in 1:length(start.pos)) {
z[i] <- substr(test,start.pos[i],end.pos[i])
}
现在,您所有的变量都在列表z
中:
> z
[1] "01" "2" "002" "001" " " "14.852"
[7] "DL" " " "000000003463" "01" "003" "04660"
[13] " " NA
> z[3]
[1] "002"