2015-12-02 47 views
1

我在执行k均值在R. 在循环分配,我发起若干向量将被用于存储值属于特定簇,如在这里看到的载体:更新使用中的R

for(i in 1:k){ 
    assign(paste("cluster",i,sep=""),vector())  
    } 

然后,我想添加到特定的“聚类”向量,具体取决于我为变量getIndex获得的值。因此,如果getIndex等于2,我想将变量minimumDistance添加到称为cluster2的矢量。这就是我试图做的事:

minimumDistance <- min(distanceList) 
getIndex <- match(minimumDistance,distanceList) 
clusterName <- paste("cluster",getIndex,sep="") 
name <- c(name, minimumDistance) 

但很明显,上面的代码不会以追加到我命名我需要使用时,我实例化矢量分配为我做一个途径,因为工作。但是我不知道如何在使用粘贴的时候使用assign,也可以在添加vector时使用。

我不能使用vector [i]这样的索引,因为我不知道我想添加的特定向量的索引。我需要使用向量< - c(vector,newItem)格式,但我不知道如何在R中做到这一点。或者如果有任何其他选项,我会非常感激,非常感谢。如果我使用的是Python,我会简单地使用粘贴,然后使用append,但是我不能在R中这样做。预先感谢您的帮助!

+0

基本上将R的方式做,这是创建一个列表列表元素与您当前创建的所有群集对象相对应。然后直接追加到每个列表元素。 – mts

+2

非常感谢@mts - 我将载体放入列表中,它似乎以这种方式工作。谢谢! – dahlia

回答

0

你可以做这样的事情:

out <- list() 
for (i in 1:nclust) { 
    # assign some data (in this case a list) to a cluster 
    assign(paste0("N_", i), list(...)) 
    # here I put all the clusters data in a list 
    # but you could use a similar statement to do further data manipulation 
    # ie if you've used a common syntax (here "N_" <index>) to refer to your elements 
    # you can use get to retrieve them using the same syntax 
    out[[i]] <- get(paste0("N_", i)) 
} 

如果你想有一个更完整的代码示例,这个环节听起来像一个类似的问题emclustr::em_clust_mvn