矩阵%*%矩阵中的错误:需要数字/复数矩阵/向量参数

问题描述 投票:0回答:1

我正在尝试在 R 中进行矩阵乘法。我已成功创建并运行矩阵

Matrix1
,但在尝试进行乘法时遇到错误:

Matrix1 = new("markovchain", states = c("state 1", "state 2", "state 3"),
              transitionMatrix = matrix(data = c(0,1,0,
                                                0.7,0,0.3,
                                                0.5, 0, 0.5),
                                        byrow = TRUE, nrow = 3), 
               name = "Matrix Name")

Matrix1

TwoStep = Matrix1%*%Matrix1
TwoStep

我发现Matrix1是

S4
类型。我尝试使用
as.matrix
将其转换为
S4
向量,但它不起作用:

> as.matrix(Matrix1)
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector
r matrix markov-chains
1个回答
0
投票
library(markovchain)

Matrix1 = new("markovchain", states = c("state 1", "state 2", "state 3"),
              transitionMatrix = matrix(data = c(0,1,0,
                                                 0.7,0,0.3,
                                                 0.5, 0, 0.5),
                                         byrow = TRUE, nrow = 3), 
              name = "Matrix Name")

class(Matrix1)
#> [1] "markovchain"
#> attr(,"package")
#> [1] "markovchain"
class(Matrix1[])
#> [1] "matrix" "array"


Matrix1[]%*%Matrix1[]
#>         state 1 state 2 state 3
#> state 1    0.70     0.0    0.30
#> state 2    0.15     0.7    0.15
#> state 3    0.25     0.5    0.25

创建于 2024-04-09,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.