通过fread()读取带有row.names的CSV [英] Reading CSV with row.names by fread()

查看:623
本文介绍了通过fread()读取带有row.names的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了来自 data.table 包的 fread()函数的问题。

I ran into an issue with fread() function from data.table package. I know it is still experimental, but maybe I am making some mistake somewhere.

这里是可重现的示例:

library(data.table)
test <- data.frame(a=rnorm(300), b=rnorm(300))
write.csv(test,"a.csv")
fread("a.csv")

错误:

Error in rbindlist(allargs) : 
  Item 2 has 2 columns, inconsistent with item 1 which has 3 columns

另一个问题:为什么我应该离开 row.names = TRUE write.csv 问题?到目前为止,我只有问题,因为它添加一个未命名的列到数据。

And side question: Why should I ever leave row.names=TRUE in write.csv question? So far I had only problems with it because it adds one unnamed column to the data.

Thx。

推荐答案

作为解决方法,您可以通过设置 header = FALSE

As a workaround you can read the rownames as a new column, by setting header=FALSE

fread("a.csv",header=FALSE)
header' changed by user from 'auto' to FALSE
      V1                 V2                 V3
  1:                      a                  b
  2:   1  -1.55640470495795    -1.344760319214
  3:   2   2.89752713867643   2.48413035874463
  4:   3 -0.493990961968582  0.119727513514055
  5:   4  0.559770137546773   1.07420769675405
 ---                                          
297: 296  0.585750601363698  -1.59845801200953
298: 297 -0.867339301988422  0.776738489388772
299: 298 0.0942821874550108 -0.649440075398178
300: 299 -0.308039637386426 -0.840171787291445
301: 300  0.358526722813896    -1.362322309472

fread ,它看起来所有的例子都使用 row.names = FALSE ,所以你提到这个工作正常:

From the help of fread, it looks that all the examples are using row.names=FALSE, so as you have mentioned this works fine:

write.csv(test,"b.csv",row.names=FALSE)
fread("b.csv")

这篇关于通过fread()读取带有row.names的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆