0

I have a df that looks like this:

   code.1 code.2 code.3 code.4
1:     82     93     NA     NA
2:     15     85     93     NA
3:     93     89     NA     NA
4:     81     NA     NA     NA

I'd like to generate a new df that entails all possible permutations of the columns, so for example row 5:8 would be the values of "code.2, code.3, code.4, code.1", the rows 9:12 the values of "code.3, code.4, code.1, code.2", and so on.

I've tried "permutations" from the gtools package but I keep running into "v is either non-atomic or too short"

Cos
  • 1,649
  • 1
  • 27
  • 50
  • Please share sample data and expected output and make sure they are [reproducible](http://stackoverflow.com/questions/5963269) – Sotos Apr 24 '18 at 09:26

1 Answers1

2

We can permutate the column index, select the column based on the indices, and then combine all the data frame.

library(gtools)

per <- permutations(n = 4, r = 4, repeats.allowed = FALSE)

dat2 <- do.call(rbind, lapply(1:nrow(per), function(x){
  dat_temp <- dat[, per[x, ]]
  names(dat_temp) <- names(dat)
  return(dat_temp)
  }))

head(dat2, 12)
#    code.1 code.2 code.3 code.4
# 1      82     93     NA     NA
# 2      15     85     93     NA
# 3      93     89     NA     NA
# 4      81     NA     NA     NA
# 11     82     93     NA     NA
# 21     15     85     NA     93
# 31     93     89     NA     NA
# 41     81     NA     NA     NA
# 12     82     NA     93     NA
# 22     15     93     85     NA
# 32     93     NA     89     NA
# 42     81     NA     NA     NA

DATA

dat <- read.table(text = "   code.1 code.2 code.3 code.4
1     82     93     NA     NA
2     15     85     93     NA
3     93     89     NA     NA
4     81     NA     NA     NA",
                  header = TRUE, stringsAsFactors = FALSE)
www
  • 38,575
  • 12
  • 48
  • 84
  • This is exactly what I needed, thank you! Would there be a way to exclude one or two columns from such a permutation? – Cos Apr 24 '18 at 10:27
  • @Cos Not sure how to exclude one or two columns. Perhaps you can experiment with the `permutations` function. – www Apr 24 '18 at 10:28