Rilcon42
Rilcon42

Reputation: 9763

Getting all permutations of columns

I am trying to pass all permutations of columns as a dataframe to a function, and I cant quite get my code to work. Anyone have any suggestions?

require(combinat)
indicators<-data.frame(a=c(1),b=c(2),c=c(3),d=c(4))
cols<-lapply(1:dim(indicators)[2],function(x)rbind(t(permn(1:(dim(indicators)[2]-x)))))
cols[[2]]
temp<-t(apply(cols[[2]],1,function(x){}))

GOAL

dataframe containing col: 
1
2
3
4
1,2
1,3
1,4
2,3
2,4
....

My function:

#takes in dataframe of columns
blackBox<-function(x){}

Because my original explanation wasnt clear enough: I am trying to get the columns returned in each case into a dataframe so I can do something with the data.

#testing only with the first 12 values because otherwise it takes forever
lapply(v1[1:12],function(x){
    colsCombo<-indicators[,c(eval(parse(text=x)))]
    colnames(colsCombo)
    })

Upvotes: 1

Views: 911

Answers (1)

akrun
akrun

Reputation: 887078

We could loop through the sequence of the columns, get the combn of the unlsted elements and use rapply to paste the elements in each of the nested list.

Un1 <- unlist(indicators)
lst <- lapply(seq_along(Un1), function(i) combn(Un1, i, simplify=FALSE))
v1 <- rapply(lst, toString)
v1
#[1] "1"   "2"   "3"   "4"   "1, 2"   "1, 3"   "1, 4"  "2, 3"      
#[9] "2, 4"  "3, 4"  "1, 2, 3"  "1, 2, 4"  "1, 3, 4"  "2, 3, 4"  "1, 2, 3, 4"

d1 <- data.frame(v1, stringsAsFactors=FALSE)

If we need to replace 'v1' by the column names, we can try with chartr to replace the index with the column names.

rp1 <- paste(colnames(indicators),collapse="")
pt1 <- paste(seq_along(Un1), collapse="")
chartr(pt1, rp1, v1)
#[1] "a"          "b"          "c"          "d"          "a, b"       "a, c"       "a, d"       "b, c"      
#[9] "b, d"       "c, d"       "a, b, c"    "a, b, d"    "a, c, d"    "b, c, d"    "a, b, c, d"

Or it could also be done within the combn by passing the names instead of the values.

lst <- lapply(seq_along(Un1), function(i) combn(names(Un1), i, simplify=FALSE))
v1 <- rapply(lst, toString)
v1
#[1] "a"          "b"          "c"          "d"          "a, b"       "a, c"       "a, d"       "b, c"      
#[9] "b, d"       "c, d"       "a, b, c"    "a, b, d"    "a, c, d"    "b, c, d"    "a, b, c, d"

Upvotes: 4

Related Questions