Home > front end >  R reading a non-delimited (fixed-width) datafile
R reading a non-delimited (fixed-width) datafile

Time:09-17

I have a datafile without a delineator. I have been given a data key that tells me where a variable starts--counted in the number of spaces--and the number of characters each variable is.

I'm showing a simplified version of what the data looks like below. Imagine each number in a bracket is a space in the datafile. The letters below are each variable (Variable A and B).

So, variable A starts at the 3rd space and is 2 characters long. Variable B starts at the 6th space and is 3 characters long.

[1][2][3][4][5][6][7][8][9]
       A  A     B  B  B    
       A  A     B  B  B    
       A  A     B  B  B    
       A  A     B  B  B     

 

Are there base functions or libraries in R that will allow me to read the file and convert it into a more traditional dataframe (like below)?

[VarA][VarB]
  AA   BBB 

CodePudding user response:

See read.fwf to read fixed width files:

ff <- tempfile()
cat(file = ff, "123456", "987654", sep = "\n")
read.fwf(ff, widths = c(1,2,3))    #> 1 23 456 \ 9 87 654
  • Related