с использованием expand.grid
f = function(q, p) {
as.matrix(expand.grid(replicate(p, 1:q-1L, FALSE)))
}
f(2,3)
# Var1 Var2 Var3
# [1,] 0 0 0
# [2,] 1 0 0
# [3,] 0 1 0
# [4,] 1 1 0
# [5,] 0 0 1
# [6,] 1 0 1
# [7,] 0 1 1
# [8,] 1 1 1
f(3,3)
# Var1 Var2 Var3
# [1,] 0 0 0
# [2,] 1 0 0
# [3,] 2 0 0
# [4,] 0 1 0
# [5,] 1 1 0
# [6,] 2 1 0
# [7,] 0 2 0
# [8,] 1 2 0
# [9,] 2 2 0
# [10,] 0 0 1
# [11,] 1 0 1
# [12,] 2 0 1
# [13,] 0 1 1
# [14,] 1 1 1
# [15,] 2 1 1
# [16,] 0 2 1
# [17,] 1 2 1
# [18,] 2 2 1
# [19,] 0 0 2
# [20,] 1 0 2
# [21,] 2 0 2
# [22,] 0 1 2
# [23,] 1 1 2
# [24,] 2 1 2
# [25,] 0 2 2
# [26,] 1 2 2
# [27,] 2 2 2