我有一个矩阵想要在R中进行转置,但是t()函数没有返回正确的答案。应该如何进行矩阵转置?
> 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)
。我保证你会得到正确的结果。
当你运行这个时,你会得到什么:
rm(t)
t(xx)
如果尽管我保证,它仍然无法工作,您可以完全指定您想要使用的 t()
版本,像这样:
base::t(xx)
> 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.default
被屏蔽了,或者定义了一个t.matrix
方法,那就没什么帮助了...;-) - GSeebase::t(xx)
应该首先查找 asNamespace("base")
,这样即使同名函数在其他地方注册,它也能找到 t.default()
,对吗? - Josh O'Brienqqplot
是 stats
包中的一个函数,该包已默认加载。正如你所见,创建与现有名称相同的函数可能会非常令人困惑;你应该避免这样做,并重新命名你自己的函数。 - Gregor Thomas也许你可以编写自己的函数:
xx <- matrix(c(3,7,4,8), 2, byrow = TRUE)
transp <- function(n){
TM <- matrix(, nrow = ncol(n), ncol = nrow(n))
for (i in 1 : nrow(TM)){
for (j in 1 : ncol(TM)){
TM[i, j] <- n[j, i]
}
}
print(TM)
}
transp(xx)
t
函数? - mnelmethods(t)
的输出。 - GSeet <- function(x){apply(x, 2, sd)}
。 - Dason