使用矩阵子集表

时间:2014-07-01 11:17:44

标签: r subset

我开始使用R并且我遇到了n维表my.table的问题,我希望以各种方式对其进行分组。我有一个行矩阵m,可以让我用my.table[m]选择表格的单个单元格。现在我想使用m通过指示我不想被切片的一个维i来选择表的整行(不仅是一个单元格)。通过将索引的i - 位置保留为空,可以轻松地通过常规索引来完成此操作,但在我的情况下,i的值仅在运行时已知。

我会尝试用一些代码来说明它:

# let's assume n = 4
# I can pick a cell value with the literal indexing
a.value <- my.table[2, 1, 4, 2]
# And I can reproduce this with matrix indexing
m <- matrix(c(2, 1, 4, 2), nrow=1)
a.value <- my.table[m]

# Now let's assume i = 3
# I can subset the table with literal indexing to pick the whole row
a.row <- my.table[2, 1, , 2]
# But how can I do the same using the matrix m?

我已尝试设置m[i] <- NAm[i] <- NULL,但显然它不起作用。

是否有一些“魔法”值相当于文字索引中的空格?或者没有办法直截了当地做到这一点?

更新:

我将发布我现在使用的代码,它会提供我想要的结果。不过,要知道是否有更好,更优雅或更通用的方法,这将是很好的:

function(my.table, m, i) {
    i.dim <- dim(my.table)[i]
    return(apply(matrix(1:i.dim, nrow=1), 1, function(x) {
        # in my case, I don't need to preserve the original value of m[i]
        m[i] <- x
        return(my.table[m])
    }))
}

更新2: 根据@javlacalle的要求,我发布了表格dput的输出。

structure(c(0.830412306140461, 0.169587693859539, 0.944833625218914, 
0.0551663747810858, 0.993589743589744, 0.00641025641025641, 1, 
0, 0.992307692307692, 0.00769230769230769, 1, 0, 1, 0, NaN, NaN
), class = "table", .Dim = c(2L, 2L, 2L, 2L), .Dimnames = structure(list(
    V29.0 = c("0", "1"), `779.89` = c("0", "1"), `771.81` = c("0", 
    "1"), `771.89` = c("0", "1")), .Names = c("V29.0", "779.89", 
"771.81", "771.89")))

更新3:

我发现我所谈论的“神奇”价值确实存在,你可以用bquote()得到它 - 只是我认为没有办法将它与其他数字一起使用在矩阵中形成适当的指数。

1 个答案:

答案 0 :(得分:1)

如何写作,例如my.table[1, 1, 1, 1:2]代替my.table[1, 1, 1, ]? 您可以将要扩展的索引设置为0(在m中),然后定义

f <- function(my.table, m) {
    dims <- dim(my.table)
    a <- lapply(1:4, function(x) if (m[, x] == 0) 1:dims[x] else m[, x])
    my.table[a[[1]], a[[2]], a[[3]], a[[4]]]
}

例如

m <- matrix(c(0, 1, 1, 0), nrow = 1)
my.table[, 1, 1, ] # same as my.table[1:2, 1, 1, 1:2]
#      771.89
# V29.0         0           1
#     0 0.8304123 0.992307692
#     1 0.1695877 0.007692308

f(my.table, m)
#      771.89
# V29.0         0           1
#     0 0.8304123 0.992307692
#     1 0.1695877 0.007692308
相关问题