我们说我有一个向量:
a<-c(0,0,0,0,1)
我想列出a
中恰好一位数字不同的所有向量。
所需的结果将列出向量a
0,0,0,0,0
1,0,0,0,1
0,1,0,0,1
0,0,1,0,1
0,0,0,1,1
答案 0 :(得分:2)
您可以尝试以下方法:
a <- c(0, 0, 0, 0, 1) # your input vector
m <- expand.grid(rep(list(0:1), length(a)) # all combinations of 0/1 of length a
temp <- sapply(seq_along(a), function(i) m[,i] == a[i]) # check the differences
m[rowSums(temp) == (length(a)-1),] # use the index to subset
# Var1 Var2 Var3 Var4 Var5
#1 0 0 0 0 0
#18 1 0 0 0 1
#19 0 1 0 0 1
#21 0 0 1 0 1
#25 0 0 0 1 1
答案 1 :(得分:0)
使用您提供的第一种格式:
a<-"00001"
decomp_a<-unlist(strsplit(a,""))
apply(cbind(1:length(decomp_a)),1,
function(item){decomp_a[item]<-switch(decomp_a[item],"0"="1","1"="0")
return(paste0(decomp_a,collapse=""))})
# "10001" "01001" "00101" "00011" "00000"