如何在R中提取1x1数组切片作为矩阵? [英] how to extract 1x1 array slice as matrix in R?

查看:330
本文介绍了如何在R中提取1x1数组切片作为矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用3D数组。函数从用户获取2D数组切片(矩阵),并使用行和列名称(数组的相应dimnames)将其可视化。如果数组维度> 1,它可以正常工作。

I am working with 3D arrays. A function takes a 2D array slice (matrix) from the user and visualizes it, using row and column names (the corresponding dimnames of the array). It works fine if the array dimensions are > 1.

但是,如果我有1x1x1数组,我无法将切片提取为矩阵:

However, if I have 1x1x1 array, I cannot extract the slice as a matrix:

a <- array(1, c(1,1,1), list(A="a", B="b", C="c"))

a[1,,]
[1] 1

这是一个没有dimnames的标量,因此缺少部分必要信息。如果我添加 drop = FALSE ,我没有得到矩阵但保留原始数组:

It is a scalar with no dimnames, hence part of the necessary information is missing. If I add drop=FALSE, I don't get a matrix but retain the original array:

a[1,,,drop=FALSE]
, , C = c

   B
A   b
  a 1

这些dimnames在这里,但它仍然是3维的。有没有一种简单的方法可以从1x1x1数组获得一个如上所示的矩阵切片,只是没有第三维:

The dimnames are here but it is still 3-dimensional. Is there an easy way to get a matrix slice from 1x1x1 array that would look like the above, just without the third dimension:

   B
A   b
  a 1

我怀疑问题在于索引数组,我们无法区分'take 1 value'和'take all values'以防'all'只是一个单独的...

I suspect the issue is that when indexing an array, we cannot distinguish between 'take 1 value' and 'take all values' in case where 'all' is just a singleton...

推荐答案

drop 参数是全有或全无,但 abind 包中有一个 adrop 函数,可让您选择要删除的维度:

The drop parameter of [ is all-or-nothing, but the abind package has an adrop function which will let you choose which dimension you want to drop:

abind::adrop(a, drop = 3)
##    B
## A   b
##   a 1

这篇关于如何在R中提取1x1数组切片作为矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆