如何在R中创建一个空矩阵? [英] How to create an empty matrix in R?

查看:363
本文介绍了如何在R中创建一个空矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to R. I want to fill in an empty matrix with the results of my for loop using cbind. My question is, how can I eliminate the NAs in the first column of my matrix. I include my code below:

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?

The output is the matrix I expected. The only issue is that its first column is filled with NAs. How can I delete those NAs?

推荐答案

matrix的默认值是1列.要明确拥有0列,您需要编写

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

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

A better way would be to preallocate the entire matrix and then fill it in

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

这篇关于如何在R中创建一个空矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆