R Array子集:灵活使用drop [英] R Array subsetting: flexible use of drop

查看:46
本文介绍了R Array子集:灵活使用drop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子集R数组中已经注意到:尺寸在长度为1时丢失R在进行子集设置时会掉落所有尺寸,其长度为1.

As it has been noticed in Subsetting R array: dimension lost when its length is 1 R drops every dimension when subsetting and its length is 1.

drop 属性有助于避免这种情况.我需要一种更灵活的子集方法:

The drop property helps avoid that. I need a more flexible way to subset :

> arr = array(1, dim= c(1,2,3,4))
> dim(arr[,,1,])
[1] 2 4
> dim(arr[,,1,,drop=F])
[1] 1 2 1 4

我想要一种子集的方法,即删除第3维(实际上是放置子集1的维)并保留第1维(不放置子集的维).

I want a way to subset by dropping the 3rd dimension (actually the dimension where I put the subset 1) and keepping the 1st dimension (the dimensions where no subset is put).

它应该返回维度为1 2 4的数组

It should return an array with dimension = 1 2 4

我的问题是,我开始使用无维数= 1的数组进行编码,但是当要处理维数为1的某些情况时,它会崩溃.我需要的函数提供了一种处理数组的方法,好像维数不是1.

My issue is that I started coding with an array with no dimension = 1, but when coming to deal with some cases where a dimension is 1, it crashes. The function I need provides a way to deal with the array as if the dimension is not 1.

推荐答案

执行此操作的两种方法,要么使用包 abind 中的 adrop ,要么使用完成子设置后,您选择的尺寸.

Two ways to do this, either use adrop from package abind, or build a new array with the dimensions you choose, after doing the subsetting.

library(abind)
arr  <- array(sample(100, 24), dim=c(1, 2, 3, 4))
arr2 <- adrop(arr[ , , 1, , drop=FALSE], drop=3)
dim(arr2)
arr3 <- array(arr[ , , 1 , ], dim=c(1,2,4))
identical(arr2, arr3)

如果您想要一个函数使用一个指定的边距和该边距的单个索引,然后删除该边距以创建一个正好少一个边距的新数组,这是使用 abind :

If you want a function that takes a single specified margin, and a single index of that margin, and drops that margin to create a new array with exactly one fewer margin, here is how to do it with abind:

specialsubset <- function(ARR, whichMargin, whichIndex) {
   library(abind)
   stopifnot(length(whichIndex) == 1, length(whichMargin) == 1, is.numeric(whichMargin))
   return(adrop(x = asub(ARR, idx = whichIndex, dims = whichMargin, drop = FALSE), drop = whichMargin))
}
arr4 <- specialsubset(arr, whichMargin=3, whichIndex=1)
identical(arr4, arr2)

这篇关于R Array子集:灵活使用drop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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