[R] fill up a matrix

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Apr 22 14:21:10 CEST 2004


"Luis Rideau Cruz" <Luisr at frs.fo> writes:

> Hi all,
> 
> I want to fill in this matrix vectors (by column) without overwriting the first elements in column 1995.
> 
> Is there any other way than concatenate the first element with the vector and then assign this new vector 
> to the column in matrix?   
> 
>  matrix[,"3"]<-c(1591,"vector")
>  matrix[,"4"]<-c(405,"vector")
> ...
> ...
> 
>                                matrix
>              2     3     4      5     6   7    8    9   10
> 1995  278 1591 405 482 285 99 220 48  4
> 1996 1220   NA  NA  NA  NA NA  NA NA NA
> 1997 3106   NA  NA  NA  NA NA  NA NA NA
> 1998 1895   NA  NA  NA  NA NA  NA NA NA
> 1999 1376   NA  NA  NA  NA NA  NA NA NA
> 2000  565   NA  NA  NA  NA NA  NA NA NA
> 2001  491   NA  NA  NA  NA NA  NA NA NA
> 2002 1169   NA  NA  NA  NA NA  NA NA NA
> 2003 2310   NA  NA  NA  NA NA  NA NA NA


There's a bit of formatting damage there, is this a matrix with
rownames 1995:2003 and colnames 2:10?

Have a look at this:

 m <- matrix(NA,9,9)
 m[,1] <- round(1e4*runif(9))
 m[1,] <- round(1e4*runif(9))
 colnames(m) <- 2:10
 rownames(m) <- 1995:2003
 m # should look like yours now
 m[-1,-1] <- 1:64
 m

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list