在R数据框中创建所有可能的列置换 [英] Create all possible column permutations in R dataframe
问题描述
我有一个看起来像这样的df:
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
我想生成一个新的df,其中包含列的所有可能排列,因此例如第5:8行将是"code.2, code.3, code.4, code.1"
的值,第9:12行将是"code.3, code.4, code.1, code.2"
的值,并且等等.
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.
我已经尝试过从gtools包中进行排列",但是我一直遇到"v要么是非原子的,要么太短"的情况.
I've tried "permutations" from the gtools package but I keep running into "v is either non-atomic or too short"
推荐答案
我们可以排列列索引,根据索引选择列,然后组合所有数据框.
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
数据
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)
这篇关于在R数据框中创建所有可能的列置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!