尝试在 R 中创建具有转换规则的矩阵
Trying to create a matrix with transition rules in R
我是 R 的新手,我正在尝试创建如下所示的矩阵:
enter image description here
逻辑是,对于每一行 (x),如果值对应于第 1 列 (y=0),则减去一个点。否则,对于其余列 (y>=1) 值向右移动的每一步,添加两个点,最大值 =8。
我试过的是以下但它不能正常工作:
m=9
n=5
test=matrix(0,m,n)
rownames(test) <- c("0","1","2","3","4","5","6","7","8")
colnames(test) <- c("O","1","2","3",">=4")
test
for (i in 1:dim(test)[1]) {
for (j in 1:dim(test)[2]) {
if (j<=1) {
test[i,j] = i-2
}
else
{
test[i,j] = i+2
}
}
}
test[test > 8] <- 8
test[test < 0] <- 0
print (test)
如有任何建议或帮助,我们将不胜感激。
一个选项是 shift
来自 data.table
library(data.table)
v1 <- 8:0
out <- cbind(shift(v1, type = 'lead', fill = 0),
do.call(cbind, shift(v1, n = seq(min(v1), max(v1), by = 2),
type = 'lag', fill = max(v1))))[, c(2, 1, 3:6)]
row.names(out) <- rev(v1)
colnames(out) <- c("x/y", "O","1","2","3",">=4")
out
# x/y O 1 2 3 >=4
#0 8 7 8 8 8 8
#1 7 6 8 8 8 8
#2 6 5 8 8 8 8
#3 5 4 7 8 8 8
#4 4 3 6 8 8 8
#5 3 2 5 7 8 8
#6 2 1 4 6 8 8
#7 1 0 3 5 7 8
#8 0 0 2 4 6 8
我是 R 的新手,我正在尝试创建如下所示的矩阵: enter image description here
逻辑是,对于每一行 (x),如果值对应于第 1 列 (y=0),则减去一个点。否则,对于其余列 (y>=1) 值向右移动的每一步,添加两个点,最大值 =8。 我试过的是以下但它不能正常工作:
m=9
n=5
test=matrix(0,m,n)
rownames(test) <- c("0","1","2","3","4","5","6","7","8")
colnames(test) <- c("O","1","2","3",">=4")
test
for (i in 1:dim(test)[1]) {
for (j in 1:dim(test)[2]) {
if (j<=1) {
test[i,j] = i-2
}
else
{
test[i,j] = i+2
}
}
}
test[test > 8] <- 8
test[test < 0] <- 0
print (test)
如有任何建议或帮助,我们将不胜感激。
一个选项是 shift
来自 data.table
library(data.table)
v1 <- 8:0
out <- cbind(shift(v1, type = 'lead', fill = 0),
do.call(cbind, shift(v1, n = seq(min(v1), max(v1), by = 2),
type = 'lag', fill = max(v1))))[, c(2, 1, 3:6)]
row.names(out) <- rev(v1)
colnames(out) <- c("x/y", "O","1","2","3",">=4")
out
# x/y O 1 2 3 >=4
#0 8 7 8 8 8 8
#1 7 6 8 8 8 8
#2 6 5 8 8 8 8
#3 5 4 7 8 8 8
#4 4 3 6 8 8 8
#5 3 2 5 7 8 8
#6 2 1 4 6 8 8
#7 1 0 3 5 7 8
#8 0 0 2 4 6 8