沿数组中的 n 维之一选择 [英] Select along one of n dimensions in array

查看:19
本文介绍了沿数组中的 n 维之一选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有一个数组,由这样的函数创建:

I have an array in R, created by a function like this:

A <- array(data=NA, dim=c(2,4,4), dimnames=list(c("x","y"),NULL,NULL))

而且我想沿一个维度进行选择,因此对于上面的示例,我将有:

And I would like to select along one dimension, so for the example above I would have:

A["x",,]
dim(A["x",,])    #[1] 4 4

如果我事先不知道我的数组可能有多少维(除了我想选择的已命名维),有没有一种方法可以概括?我想编写一个函数,该函数接受可能格式化为上述 A 的输入,或者:

Is there a way to generalize if I do not know in advance how many dimensions (in addition to the named one I want to select by) my array might have? I would like to write a function that takes input that might formatted as A above, or as:

B <- c(1,2)
names(B) <- c("x", "y")

C <- matrix(1, 2, 2, dimnames=list(c("x","y"),NULL))

背景

一般背景是我正在研究 ODE 模型,因此对于 deSolve 的 ODE 函数,它必须采用具有我当前状态的单个命名向量.对于其他一些函数,比如计算相平面/方向场,使用更高维的数组来应用微分方程会更实用,我想避免有许多相同函数的副本,只是使用不同的我要选择的维度后的逗号数.

Background

The general background is that I am working on an ODE model, so for deSolve's ODE function it must take a single named vector with my current state. For some other functions, like calculating phase-planes/direction fields, it would be more practical to have a higher-dimensional array to apply the differential equation to, and I would like to avoid having many copies of the same function, simply with different numbers of commas after the dimension I want to select.

推荐答案

我花了很多时间来找出对 plyr 执行此操作的最快方法,而我能想到的最好方法是手动构建对 <代码>[:

I spent quite a lot of time figuring out the fastest way to do this for plyr, and the best I could come up with was manually constructing the call to [:

index_array <- function(x, dim, value, drop = FALSE) { 
  # Create list representing arguments supplied to [
  # bquote() creates an object corresponding to a missing argument
  indices <- rep(list(bquote()), length(dim(x)))
  indices[[dim]] <- value

  # Generate the call to [
  call <- as.call(c(
    list(as.name("["), quote(x)),
    indices,
    list(drop = drop)))
  # Print it, just to make it easier to see what's going on
  print(call)

  # Finally, evaluate it
  eval(call)
}

(您可以在 https://github.com/hadley/devtools/wiki/Computing-on-the-language)

然后您可以按如下方式使用它:

You can then use it as follows:

A <- array(data=NA, dim=c(2,4,4), dimnames=list(c("x","y"),NULL,NULL))
index_array(A, 2, 2)
index_array(A, 2, 2, drop = TRUE)
index_array(A, 3, 2, drop = TRUE)

如果您想基于多个维度进行提取,它也会以一种直接的方式概括,但您需要重新考虑函数的参数.

It would also generalise in a straightforward way if you want to extract based on more than one dimension, but you'd need to rethink the arguments to the function.

这篇关于沿数组中的 n 维之一选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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