保留csv数据子集的行名称

时间:2013-07-16 16:07:35

标签: r

我在 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])不会保留我想要的行名称。

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

1 个答案:

答案 0 :(得分: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