15

I'm trying to read a file into R using data.table / fread. Some of the fields have leading zeros and I just want to read the data in as characters and manually fix them. However I can't figure out how to convey this to fread. I'm trying this and it's assigning char, num, etc types as it normally would :

prop1 <- data.frame(fread("C:\\myFile.csv"), stringsAsFactors = F, colClasses = c(rep('character',58)))

What am I missing?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
screechOwl
  • 27,310
  • 61
  • 158
  • 267

2 Answers2

27

Your colClasses argument is in the wrong place. It needs to be inside fread(), not inside data.frame(). Try this:

prop1 <- data.frame(fread("C:\\myFile.csv", 
                          colClasses = c(rep("character", 58))),
                    stringsAsFactors = FALSE)

More canonical use of data.table to accomplish this would be:

prop1 <- fread("C:\\myfile.csv", colClasses = 'character', data.table = FALSE)
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
neilfws
  • 32,751
  • 5
  • 50
  • 63
  • @MichaelChirico how would I specify the class for one column and then just let fread automatically guess the classes for the remaining columns? – user2205916 Feb 17 '18 at 05:32
  • @user2205916 Use `colClasses = list(character = 'known_char_col')`, i.e., pass the known column's type in the `list` format, see `?fread` – MichaelChirico Feb 17 '18 at 07:01
  • @MichaelChirico I don't understand. My question, posed more clearly: https://stackoverflow.com/questions/48838222/r-data-tablefread – user2205916 Feb 17 '18 at 07:06
9

simply put:

colClasses=c("character")
Vitalijs
  • 938
  • 7
  • 18
  • 2
    I know you are trying to be simple ,,, but some extra text will help people to consider it as complete answer :) prop1 <- fread("C:\\myfile.csv", colClasses = 'character', data.table = FALSE) – Puneet Sinha Jan 18 '19 at 06:53