如果通常的"t()"不起作用,如何在r中转置矩阵? [英] how to transpose a matrix in r if the usual `t( )` doesn't work?

查看:175
本文介绍了如果通常的"t()"不起作用,如何在r中转置矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在R中转置的矩阵,但t()函数未返回正确的答案.如何转置矩阵?

I have a matrix I am trying to transpose in R but the t() function does not return the right answer. How can I transpose the matrix?

> xx=matrix(c(3,7,4,8),2,byrow=TRUE)
> xx
     [,1]  [,2]
[1,]    3     7
[2,]    4     8
> t(xx)
[1] 0.7071068 0.7071068

推荐答案

这个答案是不正确的,但是对我有启发性,也许对其他人有启发性,所以我将它保留.

如@mnel所述,基本R函数t()必须被另一个同名函数屏蔽.尝试删除功能t(),然后再次执行t(xx).我保证您会得到正确的结果.

As @mnel noted, the base R function t() must be masked by another function of the same name. Try removing the function t() and doing t(xx) again. I guarantee you'll get the correct results.

运行此命令会得到什么?

What do you get when you run this:

rm(t)
t(xx)

如果(尽管我保证!)它仍然不起作用,则可以完全指定要使用的t()版本,如下所示:

If (despite my guarantee!) it still doesn't work, you can fully specify the version of t() you want to use, like this:

base::t(xx)


这就是上述两个建议不足的原因

来自?UseMethod:

命名空间可以注册通用函数的方法.支持 为此,"UseMethod"和"NextMethod"会在两个位置搜索方法: 首先在调用通用函数的环境中,然后 然后在注册数据库中找到 定义了泛型(通常是一个名称空间).所以通用的方法 该功能需要在对的调用环境中可用 通用,否则必须注册. (不管他们是否 在定义泛型的环境中可见.)

Namespaces can register methods for generic functions. To support this, ‘UseMethod’ and ‘NextMethod’ search for methods in two places: first in the environment in which the generic function is called, and then in the registration data base for the environment in which the generic is defined (typically a namespace). So methods for a generic function need to be available in the environment of the call to the generic, or they must be registered. (It does not matter whether they are visible in the environment in which the generic is defined.)

我错误地认为S3方法分派在base:::.__S3MethodsTable__.中寻找t.default() first 之类的方法,而在asNamespace("base") 之前寻找 >在调用环境中查看,反之则更接近事实.

I wrongly assumed that S3 method dispatch looks for methods like t.default() first in base:::.__S3MethodsTable__. and then perhaps in asNamespace("base")before looking in the calling environment, whereas the reverse is closer to the truth.

通过GSee编辑

这里是一个交互式会话,以演示可能是问题所在.

Here's an interactive session to demonstrate what could have been the problem.

> t <- function(x, ...) print("generic masked")
> t.default <- function(x, ...) print("t.default masked")
> t.matrix <- function(x, ...) print("t.matrix was used")
> t.numeric <- function(x, ...) print("t.numeric was used")
> xx=matrix(c(3,7,4,8),2,byrow=TRUE)
> t(xx)
[1] "generic masked"
> base::t(xx)
[1] "t.matrix was used"
> rm(t.matrix)
> base::t(xx)
[1] "t.numeric was used"
> rm(t.numeric)
> base::t(xx)
[1] "t.default masked"
> rm(t.default)
> base::t(xx)
     [,1] [,2]
[1,]    3    4
[2,]    7    8

这篇关于如果通常的"t()"不起作用,如何在r中转置矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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