2
votes

I'm trying to import a text file into R which has several columns separated by several spaces. It also contains words which are also separated by spaces. I've tried a lot with the read.table() command. When I use sep = "" R recognises the columns but places each word in a separate column. I could combine these columns but different rows contain a different amounts of words. Example of a row in the text file:

123A456B789C0 RADIO PANEL 95-17 AB123 0 1 0987AB654321C ALTIMETER 12-34 123AB 1 2 1234567890ABC LIGHT SENSOR BACK 78-45 ABC12 0 1

How can I fix this?

1

1 Answers

2
votes

The read.fwf function (read a table of fixed width formatted data into a data.frame) is what you're looking for. With your example above:

read.fwf(file = "test", widths = c(16, 20, 12, 13, 8, 1), strip.white = T)

             V1                V2    V3    V4 V5 V6
1 123A456B789C0       RADIO PANEL 95-17 AB123  0  1
2 0987AB654321C         ALTIMETER 12-34 123AB  1  2
3 1234567890ABC LIGHT SENSOR BACK 78-45 ABC12  0  1

file is your source file, widths is an integer vector with the successive widths of all columns, and you can add strip.white = T so that unnecessary spaces are trimmed for each value.