Question

I have data code conatin data like this

dat<-data.frame(A=c("V1","V2","V3","V4"), B=c("V1","V2","V3","V5"))

I would like to take combination of each one and print output as

output of A

V1=>V2V3V4

V2=>V1V3V4

V3=>V1V2V4

V1V2=>V3V4

V1V3=>V2V4

V3V4=>V1V2

V2V4=>V1V3

V2V3V4=>V1

V1V3V4=>V2

V1V2V4=>V3

similar way B combination my code is

vd<-data.frame()
vd<-data.frame(A=c("V1","V2","V3","V4"),B=c("V1","V2","V3","V4")) 
vf<-length(vd)
i<-1
while(i<=vf)
{
vd<-dat[,i]
leng<-nrow(dat)
selectru<-combn(vd,leng)
fst<-selectru[i]
select<-data.frame()
select<-selectru[selectru[,1]!=selectru[i],]
m<-length(select)
select<-combn(select,m)
snd <-apply(select,2,function(rows) paste0(rows, collapse = ""))
cat(sprintf("\"%s\" =>\"%s\"\n", fst, snd))
i<-i+1
}

this code is not working. I cant store multiple combination in single data.frame. thats the problem

Was it helpful?

Solution

Your desired output seems a bit strange (multiple combinations are the same), but I understand it might be hard to explain what you want. The following code might give you some inspiration. It takes all combinations and in front of the => it shows whats not included in that combination.

dat<-data.frame(A=c("V1","V2","V3","V4"),B=c("V1","V2","V3","V4")) 
for (h in 1:ncol(dat)) {
  for (i in 1:(nrow(dat)-1)) {
    combinations1 <- combn(nrow(dat), i)

    for (j in 1:ncol(combinations1)) {
      k <- combinations1[,j]
      a <- (dat[k,h])
      a <- paste(a, sep="", collapse="") 
      b <-(dat[-k,h])
      b <- paste(b, sep="", collapse="") 
      cat(sprintf("\"%s\" =>\"%s\"\n", a, b))
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top