我正在发布代码,因为它会出现在我的程序中,以更好地说明我面临的挑战。
N = 6
land_l = rep(list(0:1), N)
land_pos = expand.grid(land_l) #gives a list of all permutations
h = 2 # the position in land_pos of interest, here [2]
k = list(c(2, 4, 5), c(4,5)) #representative list structure of a list of other elements
start_pos = matrix(c(0,1,1,1,0,1), nrow=1, ncol=6, byrow=TRUE)
perm_pos = matrix(start_pos, nrow = 2^length(k[[1]]), ncol = N, byrow = TRUE )
我现在想更改矩阵"perm_pos",以便它反映 h 和 k[[1]] 的所有可能排列,不包括自身。也就是说,h = 2,k[[1]] 是 2、4、5。我正在寻找元素 2、4、5 的所有排列(即 0 0 0、1 0 0、1 1 0 等,而perm_pos中的其他元素保持原样(。
然后perm_pos应该看起来像这样(每个唯一排列发生的行的顺序并不重要(:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 1 1 1 0 1
[2,] 0 1 1 1 1 1
[3,] 0 1 1 0 0 1
[4,] 0 1 1 0 1 1
[5,] 0 0 1 1 0 1
[6,] 0 0 1 1 1 1
[7,] 0 0 1 0 0 1
[8,] 0 0 1 0 1 1
感谢您的帮助!
可能的解决方案如下。
tmp_l = rep(list(0:1), length(k[[1]]))
tmp_pos = expand.grid(tmp_l)
perm_pos_adj = perm_pos
for(i in 1:nrow(tmp_pos))
{
counter = 0
for(j in k[[1]])
{
counter = counter+1
perm_pos_adj[i,j] = tmp_pos[i,counter]
}
}
perm_pos_adj提供搜索结果。