[R] Initializing vector and matrices

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Thu Feb 29 11:28:53 CET 2024


x <- numeric(0)
for (...) {
    x[length(x)+1] <- ...
}
works.
You can build a matrix by building a vector one element at a time this way,
and then reshaping it at the end.  That only works if you don't need it to be
a matrix at all times.
Another approach is to build a list of rows.  It's not a matrix, but a list of
rows can be a *ragged* matrix with rows of varying length.

On Wed, 28 Feb 2024 at 21:57, Steven Yen <styen using ntu.edu.tw> wrote:
>
> Is there as way to initialize a vector (matrix) with an unknown length
> (dimension)? NULL does not seem to work. The lines below work with a
> vector of length 4 and a matrix of 4 x 4. What if I do not know
> initially the length/dimension of the vector/matrix?
>
> All I want is to add up (accumulate)  the vector and matrix as I go
> through the loop.
>
> Or, are there other ways to accumulate such vectors and matrices?
>
>  > x<-rep(0,4)  # this works but I like to leave the length open
>  >  for (i in 1:3){
> +  x1<-1:4
> +  x<-x+x1
> + }
>  > x
> [1]  3  6  9 12
>
>  > y = 0*matrix(1:16, nrow = 4, ncol = 4); # this works but I like to
> leave the dimension open
>       [,1] [,2] [,3] [,4]
> [1,]    0    0    0    0
> [2,]    0    0    0    0
> [3,]    0    0    0    0
> [4,]    0    0    0    0
>  > for (i in 1:3){
> +   y1<-matrix(17:32, nrow = 4, ncol = 4)
> +   y<-y+y1
> + }
>  > y
>       [,1] [,2] [,3] [,4]
> [1,]   51   63   75   87
> [2,]   54   66   78   90
> [3,]   57   69   81   93
> [4,]   60   72   84   96
>  >
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list