【问题标题】:Create a matrix of all the combinations (order doesn't matter) of a vector keeping their place - R创建一个保持其位置的向量的所有组合(顺序无关紧要)的矩阵 - R
【发布时间】:2015-01-05 01:29:51
【问题描述】:

我有一个字段向量

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

我希望能够创建具有顺序无关紧要的所有组合的字符串('E'、'F' 与 'F'、'E' 相同)。

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

# 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 ) ))
}

在这些组合中,我需要列出“地点”确实重要的字符串。如果字段不在当前组合组中,我想在它之前添加“X as”。

我现在拥有的是

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 还很陌生,所以如果有更好的方法,我会很感激提示! 谢谢!

【问题讨论】:

    标签: r combinations


    【解决方案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"
    

    【讨论】:

    • 谢谢!那太简单了!有没有办法让每一行都有'X'作为?就像第 4 行会是 'E','F' ?
    • 不确定你的意思,可能是expand.grid(Map(c, NA, x1))
    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多