【问题标题】:How to create an empty matrix in R?如何在 R 中创建一个空矩阵?
【发布时间】:2014-03-02 09:13:05
【问题描述】:

我是 R 新手。我想使用 cbind 用我的 for 循环的结果填充一个空矩阵。我的问题是,如何消除矩阵第一列中的 NA。我在下面包含我的代码:

output<-matrix(,15,) ##generate an empty matrix with 15 rows, the first column already filled with NAs, is there any way to leave the first column empty?

for(`enter code here`){
  normF<-`enter code here`
  output<-cbind(output,normF)
}

输出是我期望的矩阵。唯一的问题是它的第一列充满了 NA。如何删除这些 NA?

【问题讨论】:

  • 在 R 中这是一个非常糟糕的主意。不断增长的结构使代码非常缓慢。

标签: r matrix na


【解决方案1】:

matrix 的默认值为 1 列。要明确有 0 列,您需要编写

matrix(, nrow = 15, ncol = 0)

更好的方法是预先分配整个矩阵,然后将其填充

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

【讨论】:

  • 我发现在第二种方法中,如果向量大小未知,则第三行将是mat[1:length(vector), column] &lt;- vector,以允许对矩阵进行NA填充。
  • 效果很好!如果您像我一样神经质,并且想避免使用感叹号指出“函数缺少参数”,那么您可以只使用 matrix(NA, nrow = 15, ncol = 0) 而不是 matrix(, nrow = 15, ncol = 0)
【解决方案2】:

如果您事先不知道列数,请将每一列添加到列表中,并在末尾添加cbind

List <- list()
for(i in 1:n)
{
    normF <- #something
    List[[i]] <- normF
}
Matrix = do.call(cbind, List)

【讨论】:

    【解决方案3】:

    我会谨慎地认为某事是一个坏主意,因为它很慢。如果它是不需要太多时间执行的代码的一部分,那么速度就无关紧要了。我只是使用了以下代码:

    for (ic in 1:(dim(centroid)[2]))
    {
    cluster[[ic]]=matrix(,nrow=2,ncol=0)
    }
    # code to identify cluster=pindex[ip] to which to add the point
    if(pdist[ip]>-1)
    {
    cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
    }
    

    针对在不到 1 秒内运行的问题。

    【讨论】:

      【解决方案4】:

      要删除 NA 的第一列,您可以使用负索引(从 R 数据集中删除索引)。 例如:

      output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6
      
      # output = 
      #           [,1] [,2] [,3]
      #     [1,]    1    3    5
      #     [2,]    2    4    6
      
      output = output[,-1] # this removes column 1 for all rows
      
      # output = 
      #           [,1] [,2]
      #     [1,]    3    5
      #     [2,]    4    6
      

      所以您可以在原始代码中的 for 循环之后添加 output = output[,-1]

      【讨论】:

      • 或者在克里斯托弗的回答中,您可以从一个没有列的矩阵作为output = matrix(,15,0)
      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      相关资源
      最近更新 更多