创建一个保持其位置的向量的所有组合(顺序并不重要)的矩阵 - R.

时间:2015-01-04 16:19:16

标签: r combinations

我有一个字段向量

cuchars <- c('E', 'F', 'G')

我希望能够创建包含订单无关紧要的所有组合的字符串(&#39; E&#39;&#39; F&#39;与&#39相同; F&#39;&#39; E&#39)

我能够创建一个包含我需要的所有组合的矩阵。

# make a dataframe with all our possible combinations
combi <- data.frame(matrix(nrow=0,ncol=length(cuchars)))
for(i in 1:length(cuchars)){
  combi.tmp <- t(combn(cuchars,i))
  combi <- rbind(combi,cbind(combi.tmp, matrix(nrow=nrow(combi.tmp), ncol=length(cuchars)-i ) ))
}

在这些组合中,我需要列出一个字符串列表,其中&#34;放置&#34;确实很重要。如果字段不在当前组合组中,我想将&#39; X添加为&#39;在它之前。

我现在拥有的是

for(i in 1:length(combi)){
   filter <- paste0(combi[i,][!is.na(combi[i,])],collapse=', ')
   missing <- setdiff(cuchars, paste0(combi[i,][!is.na(combi[i,])]))
   missing <- ifelse(length(missing) != 0 ,paste0( " 'X' as ", missing ,collapse=', '),'') 
   print( paste0( filter, ifelse(missing != '',paste0(', ',missing,collapse=', '),'') )
}

E,   'X' as F,  'X' as G
F,   'X' as E,  'X' as G
G,   'X' as E,  'X' as F
E,   F,         'X' as G
E,   G,         'X' as F
F,   G,         'X' as E
E,   F,          G

我需要的是:(保持E,F和G的顺序)

E,         'X' as F,     'X' as G
'X' as E,  F,            'X' as G
'X' as E,  'X' as F,     G
E,         F,            'X' as G
E,         'X' as F,      G 
'X' as E,  F,             G
E,         F,             G

我对R来说相当新,所以如果有更好的方法可以做到这一点,我会很感激提示! 谢谢!

1 个答案:

答案 0 :(得分:1)

一个良好的开端是:

x1 <- cuchars
x2 <- sprintf("'X' as %s", cuchars)
expand.grid(Map(c, x1, x2))

#          E        F        G
# 1        E        F        G
# 2 'X' as E        F        G
# 3        E 'X' as F        G
# 4 'X' as E 'X' as F        G
# 5        E        F 'X' as G
# 6 'X' as E        F 'X' as G
# 7        E 'X' as F 'X' as G
# 8 'X' as E 'X' as F 'X' as G

如果您不想要最后一行,请使用head删除它:

head(expand.grid(Map(c, x1, x2)), -1)

输出是一个包含三列的data.frame。您可以通过执行以下操作将其转换为字符向量:

do.call(paste, c(head(expand.grid(Map(c, x1, x2)), -1), sep = ", "))
# [1] "E, F, G"               "'X' as E, F, G"        "E, 'X' as F, G"       
# [4] "'X' as E, 'X' as F, G" "E, F, 'X' as G"        "'X' as E, F, 'X' as G"
# [7] "E, 'X' as F, 'X' as G"