3
votes

As an simple example, I write cars out without column names.

data.table::fwrite(cars, "cars.csv", col.names = FALSE)

and then I try to read them in with column names and by specifying the type of column a

data.table::fread("cars.csv", col.names = c("a","b"),
                  colClasses = list(a = "numeric"))

and I get this error

Error in data.table::fread("cars.csv", col.names = c("a", "b"), colClasses = list(a = "numeric")) : Column name 'numeric' in colClasses[[1]] not found

2

2 Answers

4
votes

One possible solution is to use the index of the column and not the name.

data.table::fread("cars.csv", col.names = c("a","b"), colClasses = list(numeric = 1))
1
votes

It seems that data.table process the colClasses argument before col.names. Therefore, except for the workaround provided by the other answer, there are two alternative ways:

# option1: A character vector of classes
fread("cars.csv", colClasses = c(V1 = "numeric"), col.names = c("a","b"))

# option2: Or a named list of vectors of column names or numbers
fread("cars.csv", colClasses = list(numeric = "V1"), col.names = c("a","b"))

here, V1 is the auto-dectected name of the first colomn.