下面的代码展示了我如何使用Joshua Ulrich的方法创建稍微复杂一些的矩阵。希望这个答案有助于展示创建对象时可能存在的灵活性。如果没有,我可以删除我的回答。
我怀疑这种方法可以轻松修改以创建大小不同的矩阵,例如,通过将nrow或ncol设置为变量,并在matrix或rbind语句中使用rep(q, z)和某个变量z来复制向量中的元素。
p1.c1 <- 0.10
p2.c1 <- 0.20
p3.c1 <- 0.30
p4.c1 <- 0.40
s1.c1 <- matrix(c(p1.c1, p1.c1, (1 - p1.c1),
p1.c1, p1.c1, (1 - p1.c1),
0, 0, 1), nrow=3, ncol=3, byrow = TRUE)
s2.c1 <- matrix(c(p2.c1, p2.c1, (1 - p2.c1),
p2.c1, p2.c1, (1 - p2.c1),
0, 0, 1), nrow=3, ncol=3, byrow = TRUE)
s3.c1 <- matrix(c(p3.c1, p3.c1, (1 - p3.c1),
p3.c1, p3.c1, (1 - p3.c1),
0, 0, 1), nrow=3, ncol=3, byrow = TRUE)
s4.c1 <- matrix(c(p4.c1, p4.c1, (1 - p4.c1),
p4.c1, p4.c1, (1 - p4.c1),
0, 0, 1), nrow=3, ncol=3, byrow = TRUE)
n <- 5
p.c1 <- c(p1.c1, p2.c1, p3.c1, p4.c1)
for (i in 1: (n - 1)) {
assign(paste('xs', i, '.c1', sep=""), matrix(c(p.c1[i], p.c1[i], (1-p.c1[i]),
p.c1[i], p.c1[i], (1-p.c1[i]),
0, 0, 1 ), nrow=3, ncol=3, byrow = TRUE))
}
identical(xs1.c1, s1.c1)
identical(xs2.c1, s2.c1)
identical(xs3.c1, s3.c1)
identical(xs4.c1, s4.c1)
for (i in 1: (n - 1)) {
assign(paste('ys', i, '.c1', sep=""), rbind(c(p.c1[i], p.c1[i], (1-p.c1[i])),
c(p.c1[i], p.c1[i], (1-p.c1[i])),
c(0, 0, 1)))
}
identical(ys1.c1, s1.c1)
identical(ys2.c1, s2.c1)
identical(ys3.c1, s3.c1)
identical(ys4.c1, s4.c1)