0

我在csv文件中有一些数据,其中包括行名。我想获取单列数据,同时保留行名。csv文件是按以下方式生成的:

MAT <- matrix(nrow=5, ncol=2, c(1:10))
rownames(MAT) <- c("First","Second","Third","Fourth","Fifth")
write.csv(MAT, file='~/test.csv', row.names=TRUE) 

矩阵MAT如下。最终我想要这个矩阵的第一列(在加载csv文件之后),行名保持不变。

       [,1] [,2]
First     1    6
Second    2    7
Third     3    8
Fourth    4    9
Fifth     5   10

如果我现在阅读csv文件,

MAT2 <- read.csv(file='~/test.csv')

MAT2是(谁)给的

        X V1 V2
 1  First  1  6
 2 Second  2  7
 3  Third  3  8
 4 Fourth  4  9
 5  Fifth  5 10

read.csv命令似乎创建了另一行。无论如何,如果我这样做MAT3 <- MAT2[,2],我不会得到像上面这样的矩阵。as.matrix(MAT2[,2])不保留我想要的行名。

关于如何进行的任何想法?

4

1 回答 1

2

也许更好的起点是:

read.csv(file='~/test.csv', row.names = 1)
       V1 V2
First   1  6
Second  2  7
Third   3  8
Fourth  4  9
Fifth   5 10

您也可以将其包装在as.matrix

as.matrix(read.csv(file='~/test.csv', row.names = 1))

比较它们的结构:

> str(read.csv(file='~/test.csv', row.names = 1))
'data.frame':   5 obs. of  2 variables:
 $ V1: int  1 2 3 4 5
 $ V2: int  6 7 8 9 10
> str(as.matrix(read.csv(file='~/test.csv', row.names = 1)))
 int [1:5, 1:2] 1 2 3 4 5 6 7 8 9 10
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:5] "First" "Second" "Third" "Fourth" ...
  ..$ : chr [1:2] "V1" "V2"

如果您真正关心的是如何在保留原始结构的同时提取列,drop = FALSE那么您可能需要的是:

MAT2 <- as.matrix(read.csv(file='~/test.csv', row.names = 1))
#        V1 V2
# First   1  6
# Second  2  7
# Third   3  8
# Fourth  4  9
# Fifth   5 10
MAT2[, 2]
# First Second  Third Fourth  Fifth 
#     6      7      8      9     10 
MAT2[, 2, drop = FALSE]
#        V2
# First   6
# Second  7
# Third   8
# Fourth  9
# Fifth  10
于 2013-07-16T16:11:03.750 回答