LHAndersen
LHAndersen

Reputation: 121

Wrong number of columns when importing csv file

I have a dataset of 17 columns and 72920 rows. The dataset was saved form Excel to csv format. I then load it in R 3.1.2:

old<-read.table(file.choose(), header=TRUE)

str(old) 'data.frame': 72920 obs. of 1 variable: $ OID.LO.MAG.PCR.WAT.SVE.ARA.GRA.FOR.MHF.B13.B12.MTP.BI6.BI4.ALT.BI1: Factor w/ 72920 levels "1;1;0;0;0;0;0;0;0;32.00;100;420;43;72;4821;18.18;18.555",..: 1 11112 22223 33334 44445 55556 66667 70699 71810 2 ...

The problem is that R treats my dataset as being 1 column instead of 17. This is what my data looks like before exporting it:

OID LO  MAG PCR WAT SVE ARA GRA FOR MHF B13 B12 MTP BI6 BI4 ALT BI1 URB
    1   1   0   0   0   0   0   0   0   32.00   100 420 43  72  4821    18.18   18.555  1
    2   1   0   1   0   0   0   0   0   39.17   99  421 81  72  4886    20.14   18.586  0
    3   1   0   0   0   0   1   0   0   29.25   112 474 13  74  4947    132.80  18.470  0
    4   1   0   0   0   0   0   1   0   35.98   114 485 4   70  4997    166.54  18.213  0
    5   1   0   0   0   0   0   0   0   39.21   104 438 3   74  4859    54.82   18.580  1
    6   1   0   0   0   0   0   1   0   40.45   109 454 3   68  4971    107.65  18.216  0
    7   1   0   0   0   0   0   1   0   41.81   107 435 2   69  4909    46.70   18.400  0
    8   1   0   0   0   0   1   0   0   49.78   105 427 21  70  5009    18.36   18.636  0
    9   1   1   0   0   0   0   0   0   53.00   106 427 98  70  5173    13.33   18.767  0

I have tried exporting as txt as well, but when importing my data as a table I run into the same problem as above. I hope someone can help me in getting my data read correctly by R.

Upvotes: 3

Views: 4649

Answers (2)

Bas
Bas

Reputation: 1076

We need to set a separator argument with sep = ";"

More about read.table (and read.csv) can be found here.

So the code will look like this:

old <- read.table(file.choose(), header = TRUE, sep = ";")

Or instead of using read.table you can also use read.csv2() for semicolon(;) separated files, or read.csv() for comma(,) separated files. In your case this would look like this:

old <- read.csv2(file.choose(), header = TRUE) 

Upvotes: 1

Zetina
Zetina

Reputation: 87

You should specify a separator as stated here:

https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html

old <- read.table(file, header = TRUE, sep = ";")

Upvotes: 2

Related Questions