热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用动态尺寸巧妙地将R中的数组子集化?

本文介绍了如何使用动态尺寸巧妙地将R中的数组子集化。作者通过解释数组的三个维度以及第三个维度的长度可变性,提出了一种周期性子集化数组的方法,并举例说明了如何创建第二个数组。这个方法对于制作模拟模型非常有用。

I'm crafting a simulation model, and I think this problem has an easy fix, but I'm just not that used to working with arrays. Let's say I have an array, Array1, that has 3 dimensions. The first two are of constant and equal length, L, but the third dimension can be of length from 1 to X at any given time.

我正在制作一个模拟模型,我认为这个问题有一个简单的解决方法,但我只是不习惯使用数组。假设我有一个数组Array1,它有3个维度。前两个具有恒定且相等的长度L,但是在任何给定时间,第三个维度可以是从1到X的长度。

I want to be able to periodically subset Array1 to create a second array, Array2, that is composed of up to the last Y "sheets" of Array1. In other words, if the length of the third dimension of Array1 is greater than Y, then I want just the last Y sheets of Array1 but, if it's less than Y, I want all sheets of Array1.

我希望能够定期将Array1子集创建第二个数组Array2,该数组由Array1的最后Y个“表”组成。换句话说,如果Array1的第三个维度的长度大于Y,那么我只想要最后的Y个Array1,但是,如果它小于Y,我想要所有的Array1表。

I know that I can crudely pull this off using the tail function and a little finagling:

我知道我可以使用tail函数和一点点finagling粗略地将它拉下来:

tmp1 = tail(Array1, (L*L*Y))
Array2 = array(tmp1, dim = (L, L, (L*L/length(tmp1))))

But it seems like there could be a more elegant way of doing this. Is there an equivalent of tail for arrays in R? Or is there a way that Array2 could be produced via simple logical indexing of Array1? Or perhaps the apply function could be used somehow?

但似乎可以采用更优雅的方式来做到这一点。 R中的数组是否有等价的尾部?或者有没有办法通过Array1的简单逻辑索引生成Array2?或许也可以以某种方式使用apply函数?

1 个解决方案

#1


1  

Were you after something like this?

你之后是这样的吗?

a <- array(1:(3*4*5), dim=c(3,4,5))
x <- dim(a)[3]
y <- 2
a[, , seq(to=x, len=min(x, y))]

, , 1

     [,1] [,2] [,3] [,4]
[1,]   37   40   43   46
[2,]   38   41   44   47
[3,]   39   42   45   48

, , 2

     [,1] [,2] [,3] [,4]
[1,]   49   52   55   58
[2,]   50   53   56   59
[3,]   51   54   57   60

推荐阅读
author-avatar
爱我独自等待_白兔窝2013
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有