尝试用R中的转换规则创建矩阵

我是R的新手,我正在尝试创建一个如下所示的矩阵: enter image description here

逻辑是对于每一行(x),如果值对应于第一列(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",">=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)

任何建议或帮助将不胜感激。

oyangnann 回答:尝试用R中的转换规则创建矩阵

一个选项是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
本文链接:https://www.f2er.com/3127434.html

大家都在问