在由R读取的数据文件中分配列名

时间:2016-08-02 02:52:13

标签: r data-mining data-science

我正在尝试读取R中的网络数据(ids图)。该文件名为' network.txt'和数据如下:

4 0
5 0
6 0
7 0
8 0
9 0
4029 1
4030 1
4031 1
4032 1
4033 1
19088 9040
19089 9040
19090 9040
19091 9040
19092 9040
19093 9040
19094 9040
19095 9040
19096 9040
19097 9040

而且,我正在使用read.table()模块阅读它。

data = read.table("network.txt",sep="\t",header=FALSE)
colnames( data ) <- unlist(c('to', 'from'))

Error in `colnames<-`(`*tmp*`, value = c("to", "from")) : 
  'names' attribute [2] must be the same length as the vector [1]

那么,如何分配列名?读取原始数据文件有什么错误吗?

2 个答案:

答案 0 :(得分:4)

您可以在read.table函数调用中提供列名称,如下所示:

read.table("network.txt", col.names = c("Col1", "Col2"))

或者,您也可以采用与names函数尝试类似的方式执行此操作:

test1 <- read.table("Question1.txt")
names(test1) <- c("col1", "col2")

答案 1 :(得分:2)

我们只需要

colnames( data ) <- c('to', 'from')

c('to', 'from')返回vectorunlist在此处不执行任何操作。 unlist用于输出为listdata.frame的情况,list也是length,其元素等于columns又名sep

关于错误,我们可能使用错误的str(data)导致单个列,可以通过检查sep=""来识别。我会使用col.names

除了上述建议外,我们还可以在read.table

中指定data <- read.table("network.txt",sep="",header=FALSE, col.names = c("to", "from"))
fread

或者使用data.table中的library(data.table) data <- fread("network.txt", header=FALSE, col.names = c("to", "from")) (自动获取分隔符)

{{1}}