如何在R中创建一个空矩阵?

76

我刚开始学习R语言。我想使用cbind将我的for循环的结果填入一个空矩阵中。我的问题是,如何消除矩阵第一列中的NAs。以下是我的代码:

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)
}

输出结果是我预期的矩阵。唯一的问题是它的第一列填充了NAs。如何删除这些NAs?


8
在 R 中这是个非常糟糕的想法。增长结构会使代码变得非常慢。 - Fernando
4个回答

107

matrix的默认列数为1。如果要显式地将列数设为0,需要编写:

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] <- vector,以允许矩阵进行NA填充。 - BLiu1
1
它运行得很好!如果你像我一样神经质,想要避免感叹号指出“函数缺少参数”,那么你可以使用matrix(NA, nrow = 15, ncol = 0)代替matrix(, nrow = 15, ncol = 0)。 - Rolando Gonzales

19

如果你事先不知道列数,可以将每一列添加到一个列表中,最后使用cbind函数合并。

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

7

如果某些代码执行速度很慢,不要轻易将其视为糟糕的想法。如果这部分代码执行时间很短,则速度变慢是无关紧要的。我刚刚使用了以下代码:

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秒的问题。


1
为了去除NAs的第一列,你可以使用负索引(从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]

或者按照 Christopher 的回答,你可以从一个没有列的矩阵开始,如 output = matrix(,15,0) - Sheldon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接