英文:
fread() reading everything in as 'character'
问题
抱歉,没有提供最小可重现示例(MRE)。
我正在使用fread()将大约45个不同的.csv文件堆叠在一个单独的数据框中。
dat <- fread(cmd='cat data/*.csv', header=T)
目前它正在很好地工作并且读取得很好,但每一列都被保存为字符,尽管大约90%的列实际上都是数值型。
dat <- fread(cmd='cat data/*.csv', header=T, colClasses="numeric")
我尝试将所有内容强制转换为数值型,但那没有起作用。有没有办法修复这个问题?
谢谢!
英文:
Apologies straight away for no MRE.
I am using fread() to pile about 45 different .csv files one on top of each other in a single dataframe.
dat<-fread(cmd='cat data/*.csv, header=T)
I copied this from webb's answer to this question.
It's working well and reading in nicely, but every column is being saved as character at the moment when about 90% of them are actually numeric.
dat<-fread(cmd='cat data/*.csv, header=T,colClasses="numeric")
I tried to coerce everything to numeric but that didn't work. Is there any way to fix this
Thanks!
答案1
得分: 1
尝试这个(data.table)方法:
library(data.table)
files.to.read <- list.files(path = "./data",
pattern = ".*\\.csv$",
full.names = TRUE,
recursive = FALSE)
L <- lapply(files.to.read, fread)
DT <- rbindlist(L, use.names = TRUE, fill = TRUE)
我使用了3行代码以增强可读性。但如果需要的话,你可以轻松地将它们转换为一行。
英文:
Try this (data.table) approach
library(data.table)
files.to.read <- list.files(path = "./data",
pattern = ".*\\.csv$",
full.names = TRUE,
recursive = FALSE)
L <- lapply(files.to.read, fread)
DT <- rbindlist(L, use.names = TRUE, fill = TRUE)
I used 3 lines of code for readability. But you van easily convert them to a single line if needed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论