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

查看:70
本文介绍了沿数组中的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天全站免登陆