2

我想以一般方式提出的非常简单的问题,因为它似乎是一个反复出现的问题,我很高兴找到一种通用的方法来解决这个问题。问题是将逻辑矩阵转换为因子矩阵,例如,但要保持矩阵结构:行数和列数、列名、行名。我想要一些比

X2 <- matrix(as.mode(X), ncol=ncol(X)); 
rownames(X2) <- rownames(X) ...

我已经在某些情况下发现了这个问题,所以我把它放在这里,但还有一些问题......

A. into (-->) 因素是我没有一个简单的方法。

B. 1. 逻辑 --> 数字:使用 '+0' 技巧

BoolMatrix <- matrix(c(TRUE,FALSE),nrow=3,ncol=2)
rownames(BoolMatrix) <- LETTERS[1:3]; colnames(BoolMatrix) <-LETTERS[11:12]
(NumMatrix <- BoolMatrix + 0)   

B. 2. numeric --> logical:直接使用条件

NumMatrix <- matrix(1:6, ncol=2)
rownames(NumMatrix) <- LETTERS[1:3]; colnames(NumMatrix) <-LETTERS[11:12]
(BoolMatrix <- NumMatrix == 0) 

C. numeric <--> 字符:不能比 2 衬里做得更好,直接改变模式有效(也可以在逻辑和数字之间工作,但上述解决方案更优雅)

CharMatrix <- NumMatrix
mode(CharMatrix) <-"character"
print(CharMatrix)

最后一个解决方案(“2 liner”)实际上适用于与因素无关的任何事情,我遇到了困难......

任何想法 ?:-)

4

3 回答 3

5

使用structure,它将属性列表附加到任意对象。对于矩阵,您想要的属性是dim,并且,可选地,dimnames

例如转换X为因子矩阵:

m <- structure(factor(X), dim=dim(X), dimnames=dimnames(X))
于 2013-08-06T04:36:48.673 回答
2

在@HongOoi 的出色答案的基础上,这里有一个函数将保留所有attributes输入矩阵(包括维度和维度名称)并将数据更改为所需的modenumeric mode, factor class

change.mat <- function(X,ch.fun) {
  do.call(structure,c(list(.Data=do.call(ch.fun,list(X))),attributes(X)))
}

例子:

change.mat(NumMatrix,factor)
#  K L
#A 1 4
#B 2 5
#C 3 6
#Levels: 1 2 3 4 5 6

change.mat(NumMatrix,as.character)
#  K   L  
#A "1" "4"
#B "2" "5"
#C "3" "6"

change.mat(BoolMatrix,as.numeric)
#  K L
#A 1 0
#B 0 1
#C 1 0
于 2013-08-06T04:25:35.673 回答
1

您可以简单地复制属性:

NumMatrix <- matrix(1:6, ncol=2)
rownames(NumMatrix) <- LETTERS[1:3]; colnames(NumMatrix) <-LETTERS[11:12]

FacMatrix <- as.factor(NumMatrix)
attributes(FacMatrix) <- c(attributes(FacMatrix), attributes(NumMatrix))
print(FacMatrix)
#   K L
# A 1 4
# B 2 5
# C 3 6
# Levels: 1 2 3 4 5 6
于 2013-08-06T06:21:50.570 回答