fread() 读取所有内容为’字符’。

huangapple go评论77阅读模式
英文:

fread() reading everything in as 'character'

问题

抱歉,没有提供最小可重现示例(MRE)。

我正在使用fread()将大约45个不同的.csv文件堆叠在一个单独的数据框中。

dat <- fread(cmd='cat data/*.csv', header=T)

我从这个问题的webb的答案中复制了这个

目前它正在很好地工作并且读取得很好,但每一列都被保存为字符,尽管大约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&lt;-fread(cmd=&#39;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&lt;-fread(cmd=&#39;cat data/*.csv, header=T,colClasses=&quot;numeric&quot;)

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 &lt;- list.files(path = &quot;./data&quot;, 
                            pattern = &quot;.*\\.csv$&quot;, 
                            full.names = TRUE, 
                            recursive = FALSE)
L &lt;- lapply(files.to.read, fread)
DT &lt;- 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.

huangapple
  • 本文由 发表于 2023年8月10日 13:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定