【问题标题】:update a vector using assign in R使用 R 中的分配更新向量
【发布时间】:2016-03-07 08:02:33
【问题描述】:

我正在 R 中实现 k-means。 在一个循环中,我将启动几个向量,这些向量将用于存储属于特定集群的值,如下所示:

    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)

但显然上面的代码不起作用,因为为了附加到我命名的向量,我需要像实例化向量时那样使用分配。但我不知道如何使用分配,使用粘贴时,也附加到向量时。

我不能使用诸如 vector[i] 之类的索引,因为我不知道要添加到该特定向量的哪个索引。

我需要使用矢量

【问题讨论】:

  • 基本上,R 的方法是创建一个列表,其中列表元素对应于您当前创建的所有集群对象。然后可以直接附加到每个列表元素。
  • 非常感谢@mts——我将向量放入一个列表中,它似乎以这种方式工作。谢谢!

标签: r vector append paste assign


【解决方案1】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2019-02-09
    • 2014-10-08
    • 2015-09-16
    • 2018-03-25
    相关资源
    最近更新 更多