R 列出向量的所有一位数差异

R 列出向量的所有一位数差异,r,R,假设我有一个向量: a<-c(0,0,0,0,1) 您可以尝试以下方法: 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 differ

假设我有一个向量:

a<-c(0,0,0,0,1)

您可以尝试以下方法:

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

a与您给出的第一种格式:

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"

aCan您能解释一下如何获得该结果吗?即使第一个元素也相差两位数。这些向量看起来相差不止一位数。你的编辑并没有帮助你的问题变得更清楚。也许你应该试着描述一下你想要什么。你只是想创建四个零和一个一的所有组合吗?
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"