【问题标题】:Stop `apply` from converting matrix into vector in R?停止“应用”将矩阵转换为 R 中的向量?
【发布时间】:2020-12-04 02:39:21
【问题描述】:
library(tidyverse)

假设我们有这个矩阵。我想要每一行的分位数。

m <- matrix(1:12, nrow=4)

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

如果我在 quantile 上使用带有两个参数的 apply,它会按预期工作:

m %>% 
  apply(1, quantile, probs = c(0.05, 0.9)) %>%
  t

      5%  90%
[1,] 1.4  8.2
[2,] 2.4  9.2
[3,] 3.4 10.2
[4,] 4.4 11.2

但是,如果我只向 quantile 提供 1 个参数,则输出将转换为向量。

m %>% 
  apply(1, quantile, probs = c(0.05)) %>%
  t

     [,1] [,2] [,3] [,4]
[1,]  1.4  2.4  3.4  4.4

如何将输出保留为具有正确列名的矩阵?

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    好的。首先,您的第二个结果是一个矩阵,它只是缺少列名,因为apply 的默认简化行为。要解决此问题,请使用 sapply(simplify=FALSE)lapply

    # for %>%
    library(magrittr, warn.conflicts = FALSE)
    
    m <- matrix(1:12, nrow=4)
    res1 <- m %>% 
      apply(1, quantile, probs = c(0.05, 0.9)) %>%
      t
    colnames(res1)
    #> [1] "5%"  "90%"
    
    res2 <- m %>% 
      apply(1, quantile, probs = c(0.05)) %>%
      t
    
    colnames(res2)
    #> NULL
    
    # res2 is a matrix
    inherits(res2, 'matrix')
    #> [1] TRUE
    
    # to keep the column names, use lapply then rbind
    do.call('rbind', lapply(1:nrow(m), function(i) quantile(m[i,], probs = 0.05)))
    #>       5%
    #> [1,] 1.4
    #> [2,] 2.4
    #> [3,] 3.4
    #> [4,] 4.4
    

    reprex package (v0.3.0) 于 2020 年 12 月 3 日创建

    【讨论】:

    • 唯一的小修正是apply的第二个结果是一个向量,它通过t()转换为一个矩阵
    • 是的!这有点微妙,我没有详细说明。 apply将结果“简化”为向量,转置是一个缺少列名的矩阵。
    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 2013-01-14
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2010-12-28
    相关资源
    最近更新 更多