fread - read all columns as character
Asked Answered
M

2

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?

Mandelbaum answered 25/5, 2017 at 21:58 Comment(0)
S
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)
Scratches answered 25/5, 2017 at 22:8 Comment(3)
@MichaelChirico how would I specify the class for one column and then just let fread automatically guess the classes for the remaining columns?Distillate
@Distillate Use colClasses = list(character = 'known_char_col'), i.e., pass the known column's type in the list format, see ?freadIndebtedness
@Indebtedness I don't understand. My question, posed more clearly: https://mcmap.net/q/822440/-data-table-fread-an-integer64-type-manually-override-colclass-for-only-one-columnDistillate
V
9

simply put:

colClasses=c("character")
Velasquez answered 25/5, 2017 at 22:0 Comment(1)
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)Kirit

© 2022 - 2024 — McMap. All rights reserved.