Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read table with separator = k white space with k variable

Tags:

r

text-files

I have a text file with data separated by white spaces. The number of white space is varying and I cannot use read.table. Do you have advices (ps I am on windows).

Two lines from the file:

 13001  200901010200    11.49   -23.01  -999.00
 46001  200904300200    56.30  -148.00  -999.00
like image 407
robin girard Avatar asked Jun 25 '11 07:06

robin girard


2 Answers

Even with your edit, the issue still isn't clear. Your example works for me.

Lines <-
"13001  200901010200    11.49   -23.01  -999.00
46001  200904300200    56.30  -148.00  -999.00"

con <- textConnection(Lines)
x <- read.table(con)
close(con)
x
#      V1           V2    V3      V4   V5
# 1 13001 200901010200 11.49  -23.01 -999
# 2 46001 200904300200 56.30 -148.00 -999

The default value of sep="" works because (as it says in ?read.table):

If ‘sep = ""’ (the default for ‘read.table’) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns.

like image 158
Joshua Ulrich Avatar answered Nov 14 '22 00:11

Joshua Ulrich


Using sep="" is logically equivalent to any amount of whitespace (in regex terms, "\s+").

To read your data using read.delim() or read.table(), use:

read.delim(fileName, sep="")

This also removes leading whitespace (before the first column).

like image 5
Megatron Avatar answered Nov 14 '22 00:11

Megatron