簡體   English   中英

在 R 中停止“應用”將矩陣轉換為向量?

[英]Stop `apply` from converting matrix into vector in R?

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

如果我對帶有兩個 arguments 的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 個參數,則 output 將轉換為向量。

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

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

如何將 output 保留為具有正確列名的矩陣?

好的。 首先,您的第二個結果是一個矩陣,它只是缺少列名,因為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 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM