我正在尝试将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中,这样才能正确地表示变量呢?
谢谢!
发布于 2018-06-24 11:23:50
这不是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)))发布于 2018-06-24 11:38:33
或者,这里有另一种方法,在基数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" https://stackoverflow.com/questions/51006640
复制相似问题