使用for循环

时间:2016-01-23 10:23:29

标签: r list loops

我从一组字母的所有可能组合中创建了一个矩阵列表:

vec = c('a', 'e', 'g', 'i', 'p')

现在,我想在每个列表中循环(列表具有不同的行数和列数),以便折叠每个列表的每列中的行:

temp= list(); def= list()
for (i in 1:length(vec)){
temp[[i]] <- combn(vec, i) # all combinations
for (j in 1:ncol(temp[[i]])){
def[[i]] <- matrix(paste(temp[[i]][, j], collapse=''), byrow=T)
}}

但是,我只得到每个矩阵的最后一列。例如,2个元素的组合是:

temp[[2]]
 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "a"  "a"  "a"  "a"  "e"  "e"  "e"  "g"  "g"  "i"  
[2,] "e"  "g"  "i"  "p"  "g"  "i"  "p"  "i"  "p"  "p"  

我希望我的输出为:

def[[2]]
 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "ae"  "ag"  "ai"  "ap"  "eg"  "ei"  "ep"  "gi"  "gp"  "ip"

1 个答案:

答案 0 :(得分:4)

我不确定这是你在找什么,但combn有自己的FUN参数。这意味着您可以将函数应用于每个组合(有关详细信息,请参阅?combn):

combn(vec, 2, paste0, collapse="")
#  [1] "ae" "ag" "ai" "ap" "eg" "ei" "ep" "gi" "gp" "ip"

def <- lapply(seq_along(vec), function(i)combn(vec, i, paste0, collapse=""))
def 
# [[1]]
# [1] "a" "e" "g" "i" "p"
# 
# [[2]]
#  [1] "ae" "ag" "ai" "ap" "eg" "ei" "ep" "gi" "gp" "ip"
# 
# [[3]]
#  [1] "aeg" "aei" "aep" "agi" "agp" "aip" "egi" "egp" "eip" "gip"
# 
# [[4]]
# [1] "aegi" "aegp" "aeip" "agip" "egip"
# 
# [[5]]
# [1] "aegip"
# 

BTW:你的代码问题在以下几行:

def[[i]] <- matrix(paste(temp[[i]][, j], collapse=''), byrow=T)

您始终会覆盖之前粘贴的结果(这就是您始终获得最后一列的原因)。