如何aaply使用,并保留数组维度的顺序? [英] how to use aaply and retain order of dimensions in array?

查看:215
本文介绍了如何aaply使用,并保留数组维度的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个维度的数组。我想一个函数应用到第三维,并返回一个数组。我很高兴的是,plyr :: aaply我想要做什么差不多。然而,它周围的交换我的数组的尺寸。文档告诉我,这是幂等,这(后我看着它)让我想到结构应保持不变。下面是与身份功能重复的例子。我可以修改此保留数组维度的顺序?

I have an array with 3 dimensions. I would like to apply a function to the 3rd dimension and return an array. I was very pleased that the plyr::aaply does nearly what I want. However it swaps around the dimensions of my array. The documentation told me that it is idempotent, which (after I'd looked it up) makes me think the structure should remain the same. Here's a reproducible example with the identity function. Can I modify this to retain the order of the array dimensions ?

nRow <- 10
nCol <- 10
nAge <- 7

#creating the array
dimnames <- list(NULL,NULL,NULL)
names(dimnames) <- c("x","y","age")
aF <- array(0, dim=c(nCol,nRow,nAge), dimnames=dimnames)

#aaply the identity function to the 3rd dimension
aTst <- aaply(aF, .margins=3, identity )

dim(aF)
#[1] 10 10  7
dim(aTst)
#[1]  7 10 10

查看尺寸已经从10,10,7变更为7,10,10。我知道它可以使用aperm被改回,但如果我能避免,这将是不错的。

See the dimensions have been changed from 10,10,7 to 7,10,10. I'm aware it can be changed back using aperm but if I can avoid that it would be good.

aTst2 <- aperm(aTst, c(2, 3, 1))

下面是关于什么,我其实是想用这个(感谢@Simon汉龙)做一些更多的细节。 X'放大器; Ÿ重新present二维空间,我在网格上的每个细胞年龄的载体。我想移动各年龄组,使用此功能:

Here's some more detail about what I'm actually trying to do with this (Thanks @Simon O'Hanlon). x & y represent 2D space and I have a vector of ages at each cell on the grid. I want to move each age group, using this function :

rtMove1 <- function(m, pMove=0.4) {

  #create matrices of the 4 neighbour cells to each cell
  mW = cbind( rep(0,nrow(m)), m[,-nrow(m)] )
  mN = rbind( rep(0,ncol(m)), m[-ncol(m),] )
  mE = cbind( m[,-1], rep(0,nrow(m)) )
  mS = rbind( m[-1,], rep(0,ncol(m)) )

  mArrivers <- pMove*(mN + mE + mS + mW)/4
  mStayers <- (1-pMove)*m

  mNew <- mArrivers + mStayers
  return( mNew )
}

要启动popn,将所有年龄段中的所有单元格,我可以做到这一点。

To initiate a popn, move all ages in all cells I can do this.

#initiate 100 individuals of age 3 at 5,5
aF[5,5,3] <- 100

aTst <- aaply(aF, .margins=3, rtMove1 )

aTst[3,,]

这工作在重新分配popn:

This works in redistributing the popn :

     1 2 3  4  5  6 7 8 9 10
  1  0 0 0  0  0  0 0 0 0  0
  2  0 0 0  0  0  0 0 0 0  0
  3  0 0 0  0  0  0 0 0 0  0
  4  0 0 0  0 10  0 0 0 0  0
  5  0 0 0 10 60 10 0 0 0  0
  6  0 0 0  0 10  0 0 0 0  0
  7  0 0 0  0  0  0 0 0 0  0
  8  0 0 0  0  0  0 0 0 0  0
  9  0 0 0  0  0  0 0 0 0  0
  10 0 0 0  0  0  0 0 0 0  0

但我需要使用aperm重新排列的尺寸,如果我想重复。

But I need to use aperm to rearrange the dimensions if I want to repeat.

谢谢,
刘德华

Thanks, Andy

推荐答案

您可以尝试

aTst <- aaply(aF, c(1,2,3), identity)

这是应该做的伎俩

这篇关于如何aaply使用,并保留数组维度的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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