【问题标题】:Keep column name when select one column from a data frame/matrix in R从R中的数据框/矩阵中选择一列时保留列名
【发布时间】:2015-06-02 06:10:17
【问题描述】:

在 R 中,当我从数据框/矩阵中仅选择一列时,结果将变为向量并丢失列名,如何保留列名? 例如,如果我运行以下代码,

x <- matrix(1,3,3)
colnames(x) <- c("test1","test2","test3")
x[,1]

我会得到

[1] 1 1 1

其实我想得到

     test1
[1,]     1
[2,]     1
[3,]     1

下面的代码正是我想要的,但是,有没有更简单的方法来做到这一点?

x <- matrix(1,3,3)
colnames(x) <- c("test1","test2","test3")
y <- as.matrix(x[,1])
colnames(y) <- colnames(x)[1]
y

【问题讨论】:

    标签: r


    【解决方案1】:

    问题提到“矩阵或数据框”作为输入。如果 x 是数据框,请使用 LIST SUBSETTING 表示法,这将保留列名并且默认不会简化!

    `x <- matrix(1,3,3)
    colnames(x) <- c("test1","test2","test3")
    x=as.data.frame(x)
    x[,1]
    x[1]`
    

    数据框同时具有列表和矩阵的特征:如果您使用单个向量进行子集化,它们的行为类似于列表;如果您使用两个向量进行子集化,它们的行为就像矩阵一样。 如果您选择单个,则有一个重要的区别 列:矩阵子集默认简化,列表 子集没有。 来源:详见http://adv-r.had.co.nz/Subsetting.html#subsetting-operators

    【讨论】:

      【解决方案2】:

      另一种可能是使用subset:

      > subset(x, select = 1)
      
           test1
      [1,]     1
      [2,]     1
      [3,]     1
      

      【讨论】:

        【解决方案3】:

        使用drop 参数:

        > x <- matrix(1,3,3)
        > colnames(x) <- c("test1","test2","test3")
        > x[,1, drop = FALSE]
             test1
        [1,]     1
        [2,]     1
        [3,]     1
        

        【讨论】:

          猜你喜欢
          • 2013-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多