我正在尝试读取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]
那么,如何分配列名?读取原始数据文件有什么错误吗?
答案 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')
返回vector
,unlist
在此处不执行任何操作。 unlist
用于输出为list
或data.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}}