如何在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
}