我在用R做矩阵乘法.我已经成功地创建并运行了矩阵Matrix1,但在try 乘法时发现了一个错误:

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

推荐答案

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

R相关问答推荐

使用na.locf在长格式数据集中输入具有多个时间点的数据集

如何根据包含相同值的某些列获取总额

以R为基数排列奇数个图

使用R中的gt对R中的html rmarkdown文件进行条件格式设置表的单元格

R Markdown中的交叉引用表

R:连接值,而不是变量?

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

非线性混合效应模型(NLME)预测变量的置信区间

如果可能,将数字列转换为整数,否则保留为数字

使用较长的查询提取具有部分匹配的列表中的较短目标,

传递ggplot2的变量作为函数参数—没有映射级别以正确填充美学

将Posict转换为数字时的负时间(以秒为单位)

SHINY:使用JS函数应用的CSS样式显示HTML表格

在列表中排列R数据框中的列顺序

Geom_arcbar()中出错:找不到函数";geom_arcbar";

如何在反曲线图中更改X标签

根据r中另一个文本列中给定的范围对各列求和

如何用不同长度的向量填充列表?

在直方图中显示两个变量

R中的交叉表