使用具有行和列名称的fread读取文件 [英] reading file using fread with row and column names

查看:429
本文介绍了使用具有行和列名称的fread读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用fread,如何读取包含行名和列名的CSV文件. 我尝试了以下操作,但未正确读取行和列名称.

Using fread, how to read CSV file which contains row and column names. I tried following but it is not reading the row and column names properly.

csv文件看起来像(其中C1,C2,C3是列名,而r1,r2,r3是行名)

The csv file looks like (where C1,C2,C3 are column names and r1, r2, r3 are row names)

input = ",C1,C2,C3
r1,A,B,C
r2,1,3,5
3,2,4,6"

我使用功能

require(data.table)
fread(input,header = TRUE)

给予

   r1 A B C
1: r2 1 3 5
2:  3 2 4 6

如何使用fread正确读取CSV?

How can I properly read CSV using fread?

推荐答案

您应提交错误报告.

这是一种解决方法:

colnames <- strsplit(readLines(textConnection(input), n=1), ",")[[1]]
colnames[1] <- "rownames"
setnames(DT <- fread(input, skip=1, header=FALSE), colnames)
DT
#   rownames C1 C2 C3
#1:       r1  A  B  C
#2:       r2  1  3  5
#3:        3  2  4  6

您应该知道,data.table不支持行名.

As you should know, data.table doesn't support rownames.

这篇关于使用具有行和列名称的fread读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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