9

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
  • 286,338
  • 16
  • 97
  • 143
screechOwl
  • 23,958
  • 54
  • 146
  • 246

2 Answers2

16

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
  • 31,197
  • 13
  • 98
  • 169
neilfws
  • 26,280
  • 5
  • 44
  • 53
  • @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
5

simply put:

colClasses=c("character")
Vitalijs
  • 762
  • 5
  • 16
  • 2
    I know you are trying to be simple ,,, but some extra text will help people to consider it as complete answer :) prop1 – Puneet Sinha Jan 18 '19 at 06:53