【问题标题】:Retain row names for subsets of csv data保留 csv 数据子集的行名
【发布时间】:2013-07-17 00:51:41
【问题描述】:

我在 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 &lt;- MAT2[,2],我不会得到像上面这样的矩阵。 as.matrix(MAT2[,2]) 不保留我想要的行名。

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

【问题讨论】:

    标签: r


    【解决方案1】:

    或许更好的起点是:

    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-12-23
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多