2014-02-05 584 views
41

我是R新手。我想用我的for循環使用cbind的結果來填充一個空矩陣。我的問題是,如何消除矩陣第一列中的NAs。我在下面列出了我的代碼:如何在R中創建一個空矩陣?

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?

太謝謝你了!

+5

在R這是一個非常糟糕的主意。越來越多的結構使代碼非常緩慢。 – Fernando

回答

60

matrix的默認值爲1列。要明確有0列,你需要寫

matrix(, nrow = 15, ncol = 0) 

一個更好的辦法是預先分配整個矩陣,然後在

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

填充它。如果你不知道的列數領先的時間,將每列添加到列表中,並在末尾添加cbind

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

因爲速度很慢,所以我會小心謹慎地解僱某個壞主意。如果它是代碼的一部分,不需要太多的時間來執行,那麼緩慢是無關緊要的。我剛剛使用了以下代碼:

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秒的問題。