I am new at R and I am trying to create a matrix like the following: enter image description here
The logic is that for every row (x), if value corresponds to the 1st column (y=0), then one point is subtracted. Else, for every step that value makes to the right for the rest columns (y>=1), two points are added with max value=8. What I have tried is the following but it does not work properly:
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)
Any advice or help would be much appreciated.
An option would be shift
from 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