R data.table fread: specify column data type
Asked Answered
B

2

7

Is it possible to specify the data type of numeric columns in fread? Commands like

prices = markets[, fread(paste(mkt, 'price.csv')), by = mkt]

will fail if price data are integers in one file and floats in another.

So instead of a clean one-liner, I have to explicitly write a for-loop and cast the data type to numeric and concatenate the results.

Blastosphere answered 10/4, 2019 at 10:56 Comment(0)
R
5

You can use the colClasses = argument.

fread("mytable.csv", colClasses = c("character", "character", "numeric"))

Recalesce answered 10/4, 2019 at 11:18 Comment(0)
A
5

I would suggest using the syntax

df <- fread("https://query.data.world/s/2uapynn5a5afd5dfsyaljlzhbwxoyz", colClasses=c("age" = "numeric", "job"="factor"))

The explicit specification of the variable name is more reliable.

Amby answered 27/10, 2022 at 20:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.