k.atli
k.atli

Reputation: 33

more columns than column name on txt file

I have this txt file and i would like to read this in R with this command:

read.table("C:/users/vatlidak/My Documents/Documents/Untitled.txt", header=TRUE)

R returns me the following command:

"more columns than column name"

txt file:

height Shoesize gender Location
1   181 44   male      city center
4   170 43   female    city center
5   172 43   female    city center
13  175 42   male      out of city
14  181 44   male      out of city
15  180 43   male      out of city
16  177 43   female    out of city
17  133 41   male      out of city

Upvotes: 1

Views: 5783

Answers (2)

arta
arta

Reputation: 11

It is a bit late but i had the same problem and i tried them but i did not work on my dataset, than i just converted csv file into xlsx file and it worked without any extra operation. Like,

library(gdata)
df <- read.xls(file, sheet = 1, row.names=1)

This may help for the future readers.

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269396

If myFile contains the path/filename then replace each of the first 4 stretches of whitespace on every line with a comma and then re-read using read.csv. No packages are used.

L <- readLines(myFile) ##
for(i in 1:4) L <- sub("\\s+", ",", L)
DF <- read.csv(text = L)

giving:

> DF
   height Shoesize gender    Location
1     181       44   male city center
4     170       43 female city center
5     172       43 female city center
13    175       42   male out of city
14    181       44   male out of city
15    180       43   male out of city
16    177       43 female out of city
17    133       41   male out of city

Note: For purposes of testing we can use this in place of the line marked ## above. (Note that SO can introduce spaces at the beginnings of the lines so we remove them.)

Lines <- " height Shoesize gender Location
1   181 44   male      city center
4   170 43   female    city center
5   172 43   female    city center
13  175 42   male      out of city
14  181 44   male      out of city
15  180 43   male      out of city
16  177 43   female    out of city
17  133 41   male      out of city"

L <- readLines(textConnection(Lines))
L[-1] <- sub("^\\s+", "", L[-1])

Upvotes: 1

Related Questions