以R换位的结果适用 [英] Results transposed with R apply

查看:60
本文介绍了以R换位的结果适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我只是意识到已经在此处进行了回答.

Apologies, I just realised that this has already been answered here.

这应该是非常基本的,但是我不太明白为什么会这样.有人可以帮忙吗?这是带有示例数据"的简单代码:

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"的向量,则应用" 如果为"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屋!

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