How to import txt file with uneven column numbers

43 Views Asked by At

i would like to read and tidy a large txt file in r. The file looks like this

"X1" "ID_t.x" "Pro" "Her" "We" .....(22 column) "1" 4 "string" 101 "2ndstring" NA ....(23 column) "2" 2 "xstring" 101 "ystring" 12 ....(23 column) "3" 7 "ystring" 101 "zstring" NA ....(23 column) "4" 5 "astring" 101 "bstring" NA ....(23 column)

and soon the problem is that first row is a header and 2nd row has a extra column at the beginning with row number for element making it one more column than header. The separator is a double space.It doesn't work with read.table(). I would be grateful if someone can help

I tried it line break but it wont work.

it should look like this:

"X1"  "ID_t.x"   "Pro"  "Her"       "We"  .....(22 column)

"1" 4 "string" 101 "2ndstring" NA ....(23 column) "2" 2 "xstring" 101 "ystring" 12 ....(23 column) "3" 7 "ystring" 101 "zstring" NA ....(23 column) "4" 5 "astring" 101 "bstring" NA ....(23 column)

1

There are 1 best solutions below

0
flxflks On

From the help file of the read.table command, it could work with:

?read.table
read.table(x, sep = " ", header = T, fill = T)

If it doesn't work, try to manually write the headers for each column using col.names = c() in your read.table command:

read.table(x, sep = " ", header = T, col.names = c("colname1", "colname2", etc.), fill = T)