2017-02-10 68 views
1

我有這樣read.fwf從SPSS代碼固定位置

00013   326 10 5143 1 1 11 1 73311333111111111111511111111111111111511111111111111111111111111111111111111111111111111111111   3     3  875421212454542534524542133452421245443454234234544452124445454 
00023   325 10 5143 1 1 11 1 74 1333111111111113111111111111111113111111111111111111111111111111111111111111111111111111111          864212322454542435434542143342412145443434324235454454542434543 

採樣數據,我需要讀出由從SPSS代碼固定位置,給定colume名稱和數據位置的各個數據,如圖在下面(代碼段)

ID 1-4 
QUARTER 5 
SEX 7 
AGEA 8 
AGEB 9 
RACE 10 
OCCA 11 
OCCB 12 
LOCATION 13 
REGION 14 
EDUCATION 15 
HHIA 16 
HHIB 17 
PERSONALINCOME 18 
ENGLIT 19 
CHILIT 20 
RUMILIT 21 
JAWILIT 22 
TAMILLIT 23 
MORELIT 24 
ILLITERATE 25 
MRO1 170 
MRO2 171 
MRO3 172 
MRO4 173 
MRO5 174 

我已經寫將R代碼,

data <- read.fwf("MY/Q315-Q216.txt", widths=c(-4,4,1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-144,1,1,1,1), header=FALSE, 
      col.names=c("ID", 
         "QUARTER", 
         "SEX", 
         "AGEA", 
         "AGEB", 
         "RACE" , 
         "OCCA", 
         "OCCB", 
         "LOCATION", 
         "REGION", 
         "EDUCATION", 
         "HHIA", 
         "HHIB", 
         "PERSONALINCOME", 
         "ENGLIT", 
         "CHILIT", 
         "RUMILIT", 
         "JAWILIT", 
         "TAMILLIT", 
         "MORELIT", 
         "ILLITERATE", 
         "MRO1", 
         "MRO2" , 
         "MRO3" , 
         "MRO4")) 

是否有一個更簡單的方法噸o只需使用SPSS代碼中指示的位置,而不是逐個指定寬度。

回答

0

OK,我發現它使用read_fwf功能

#read data 
library(data.table) 
library(readr) 
mydata1 <- data.table(read_fwf("MY/Q315-Q216.txt", fwf_positions(
    c(5,9,21:39,176:180), 
    c(8,9,21:39,176:180), 
    c("ID", 
    "QUARTER", 
    "SEX", 
    "AGEA", 
    "AGEB", 
    "RACE", 
    "OCCA", 
    "OCCB", 
    "LOCATION", 
    "REGION", 
    "EDUCATION", 
    "HHIA", 
    "HHIB", 
    "PERSONALINCOME", 
    "ENGLIT", 
    "CHILIT", 
    "RUMILIT", 
    "JAWILIT", 
    "TAMILLIT", 
    "MORELIT", 
    "ILLITERATE", 
    "MRO1", 
    "MRO2", 
    "MRO3", 
    "MRO4", 
    "MRO5")))