子集 R 数组:长度为 1 时维度丢失 [英] Subsetting R array: dimension lost when its length is 1

查看:27
本文介绍了子集 R 数组:长度为 1 时维度丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对数组进行子集化时,R 的行为取决于其中一个维度的长度是否为 1.如果维度的长度为 1,则该维度在子集化过程中会丢失:

When subsetting arrays, R behaves differently depending on whether one of the dimensions is of length 1 or not. If a dimension has length 1, that dimension is lost during subsetting:

ax <- array(1:24, c(2,3,4))
ay <- array(1:12, c(1,3,4))
dim(ax)
#[1] 2 3 4
dim(ay)
#[1] 1 3 4
dim(ax[,1:2,])
#[1] 2 2 4
dim(ay[,1:2,])
#[1] 2 4

在我看来,ax 和 ay 是相同的,对它们执行相同的子集操作应该返回一个具有相同维度的数组.我可以看到 R 处理这两种情况的方式可能很有用,但在我编写的代码中这是不可取的.这意味着当我将一个子集数组传递给另一个函数时,该函数将获得一个缺少维度的数组,如果我碰巧在早期阶段将维度减少到长度 1.(所以在这种情况下,R 的灵活性使我的代码不那么灵活!)

From my point of view, ax and ay are the same, and performing the same subset operation on them should return an array with the same dimensions. I can see that the way that R is handling the two cases might be useful, but it's undesirable in the code that I'm writing. It means that when I pass a subsetted array to another function, the function will get an array that's missing a dimension, if I happened to reduce a dimension to length 1 at an earlier stage. (So in this case R's flexibility is making my code less flexible!)

如何防止 R 在子集化过程中丢失长度为 1 的维度?还有另一种索引方式吗?要设置一些标志?

How can I prevent R from losing a dimension of length 1 during subsetting? Is there another way of indexing? Some flag to set?

推荐答案

正如您发现的,默认情况下 R 会删除不必要的维度.在索引时添加 drop=FALSE 可以防止这种情况:

As you've found out by default R drops unnecessary dimensions. Adding drop=FALSE while indexing can prevent this:

> dim(ay[,1:2,])
[1] 2 4
> dim(ax[,1:2,])
[1] 2 2 4
> dim(ay[,1:2,,drop = F])
[1] 1 2 4

这篇关于子集 R 数组:长度为 1 时维度丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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