R Importing several fwf into one dataframe

296 Views Asked by At

I am trying to create a DF from 11 files in .txt (fwf) format and want to use apply. I have checked and found some good advice for read.csv, but not for fwf (as you have to specify the widths)

This is how my data looks like:

AA F AD PR PA POSICION T  PESO (KG.)   UNIDADES    V.ESTADISTI  DF
10 E 01 01 AT 02101981 3 000000000053 000000000000 000000035541 01
10 E 01 01 AT 03027000 3 000000000000 000000000000 000000005940 01
10 E 01 01 AT 15091010 3 000000000012 000000000000 000000019500 01
10 E 01 01 AT 16010091 3 000000000154 000000000000 000000105195 01
10 E 01 01 AT 16024919 3 000000000015 000000000000 000000004724 01
10 E 01 01 AT 16051000 3 000000000043 000000000000 000000464400 01
10 E 01 01 AT 16059090 3 000000000006 000000000000 000000020234 01

And its kept in a directory, here a sample of names:

Files<-c("tr00an24.txt" "tr00an38.txt" "tr00an43.txt")

And so far this work for a single file:

Trade00<-read.fwf(Files[1],
                widths = c(2, 2, 3, 3, 3, 9, 2, 13, 13, 13, 3),
                colClasses = c(rep("character", 7), rep("numeric", 3), 
                                 "character"),
                header = TRUE,
                col.names = c("AA", "F", "AD", "PR", "PA", "POSICION", "T",  
                            "PESO (KG.)",   "UNIDADES",    "V.ESTADISTI",  
                            "DF")
                )

However, when I try :

   Trade00<-lapply(Files_00[1:2], read.fwf,
                      widths = c(2, 2, 3, 3, 3, 9, 2, 13, 13, 13, 3),
                      colClasses = c(rep("character", 7), rep("numeric", 3), 
                                     "character"),
                      header = TRUE,
                      col.names = c("AA", "F", "AD", "PR", "PA", "POSICION", "T",  
                                    "PESO (KG.)",   "UNIDADES",    "V.ESTADISTI", "DF") 
) 

It returns a list of DF instead of one DF. I know somehow I have to tell R to append each new DF to the existing one, but I am not able to find how.

Surely is something easy to do, but i can't find my way around it, without using a for loop...

Any advice appreciated

1

There are 1 best solutions below

0
On

Thanks!I tried do.call and this works nicely:

Trade00 <- do.call("rbind", lapply(Files_00[1:2], function(fn) 
    data.frame(Filename=fn, read.fwf(fn,
                                     widths = c(2, 2, 3, 3, 3, 9, 2, 13, 13, 13, 3),
                                     colClasses = c(rep("character", 7), rep("numeric", 3), 
                                                    "character"),
                                     header = TRUE,
                                     col.names = c("AA", "F", "AD", "PR", "PA", "POSICION", "T",  
                                                   "PESO (KG.)",   "UNIDADES",    "V.ESTADISTI",  
                                                   "DF"))
    )))