用 R 转置的结果适用 [英] Results transposed with R apply
问题描述
抱歉,我刚刚意识到这已经得到了回答这里.
这应该是非常基本的,但我真的不明白为什么会这样.有人可以帮忙吗?这是示例数据"的简单代码:
This should be pretty basic but I do not really understand why it is happening. Can someone help? This is the simple code with the example 'data':
applyDirichletPrior <- function (row_vector) {
row_vector_added <- row_vector + min (row_vector)
row_vector_result <- row_vector_added / sum(row_vector_added)
}
data <- matrix(c(1,2,3,4,5,6,7,8), nrow=2, ncol=4)
applied <- apply(data, 1, function(x) applyDirichletPrior(x))
输出如下:
> applied
[,1] [,2]
[1,] 0.1 0.1428571
[2,] 0.2 0.2142857
[3,] 0.3 0.2857143
[4,] 0.4 0.3571429
而我希望输出与输入数据的格式相同,例如:
Whereas I expect an output in the same format as the input data, like:
> applied
[,1] [,2] [,3] [,4]
[1,] 0.1000000 0.2000000 0.3000000 0.4000000
[2,] 0.1428571 0.2142857 0.2857143 0.3571429
为什么以及在apply
的哪个阶段会发生转置?
Why and at what stage during apply
is the transpose happening?
推荐答案
组合各个应用步骤的结果有点随意.您的期望有何不同?您看到的行为是文档对其的描述:
Combining the results of the individual apply steps is somewhat arbitrary. On what basis was your expectation different? The behaviour you see is how the documentation describes it:
如果每次调用‘FUN’都返回一个长度为‘n’的向量,那么‘apply’如果‘n > 1’,则返回一个维度为‘c(n, dim(X)[MARGIN])’的数组.
If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’ returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’.
请注意,您可以在之后轻松执行转置:
Note that you can easily perform the transpose afterwards:
> t(applied)
[,1] [,2] [,3] [,4]
[1,] 0.1000000 0.2000000 0.3000000 0.4000000
[2,] 0.1428571 0.2142857 0.2857143 0.3571429
这篇关于用 R 转置的结果适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!