I am trying to do matrix multiplication in R. I have successfully created and run the matrix Matrix1
, but caught an error when trying to do the multiplication:
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
I found out that Matrix1 is in S4
type. I tried to use as.matrix
to convert it from S4
into vector
but it did not work:
> 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
Created on 2024-04-09 with reprex v2.0.2