【问题标题】:Convert a matrix from mode A to mode B将矩阵从模式 A 转换为模式 B
【发布时间】:2013-08-06 04:09:53
【问题描述】:

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

更直接的东西
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.数字 字符:不能比 2 班轮做得更好,直接改变模式有效(也可以在逻辑和数字之间工作,但上述解决方案更优雅)

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

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

有什么想法吗? :-)

【问题讨论】:

  • 我认为BoolMatrix 应该更像:BoolMatrix &lt;- matrix(c(TRUE,FALSE),nrow=3,ncol=2) 否?
  • 没有mode = factor
  • @mnel - 我正要输入相同的内容,但随后@HongOoi 的答案中的mis.factoris.matrix 返回TRUE
  • @thelatemail -- 我的评论是真实的但无关紧要(因子的模式是“数字”)
  • 我仍然认为澄清mode 的意思会更好(与R 这个词的定义相比

标签: r matrix logical-operators r-factor


【解决方案1】:

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

例如将X 转换为因子矩阵:

m <- structure(factor(X), dim=dim(X), dimnames=dimnames(X))

【讨论】:

  • 正确。刚刚好。谢谢!
  • 给我带来了另一个问题:没有 SO(和其他用户提供的互联网资源),怎么会有人学习 R?没有任何路径可以引导我进入文档中的页面“结构”...
  • 除了那些不是因素。这变成了一个字符矩阵。
  • 我当然有。 mf &lt;- structure( matrix( factor(letters[10:1]), 5), dim=c(2,5) ); str(mf) #chr [1:2, 1:5] “j” “i” “h” “g” “f” “e” “d” “c” “b” “a”。 @ 987654327@ #structure(c("j", "i", "h", "g", "f", "e", "d", "c", "b", "a"), .昏暗 = c(2L, 5L))
  • structure(factor(...), dim=...),而不是structure(matrix(factor(...)), dim=...)
【解决方案2】:

基于@HongOoi 的出色答案,这里有一个函数将保留输入矩阵的所有attributes(包括维度和维度名称)并将数据更改为所需的modenumeric @987654324 @ , 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

【讨论】:

  • 谢谢,非常好的补充!
【解决方案3】:

您可以简单地复制属性:

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

【讨论】:

  • 这几乎是我想要避免做的事情,但这种形式并没有那么长或丑陋。谢谢。
  • 好吧,如果你想节省代码行数,你可以为as.*定义矩阵方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多