Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct dynamic-sized array in R

Tags:

r

I was wondering about what are the ways to construct dynamic-size array in R.

For one example, I want to construct a n-vector but its dimension n is dynamically determined. The following code will work:

> x=NULL  
> n=2;   
> for (i in 1:n) x[i]=i;  
> x  
[1] 1 2  

For another example, I want to construct a n by 2 matrix where the number of rows n is dynamically determined. But I fail even at assigning the first row:

> tmp=c(1,2)  
> x=NULL  
> x[1,]=tmp  
Error in x[1, ] = tmp : incorrect number of subscripts on matrix  
> x[1,:]=tmp   
Error: unexpected ':' in "x[1,:"  

Thanks and regards!

like image 777
Tim Avatar asked Dec 05 '10 07:12

Tim


People also ask

How do you create a dynamic array size?

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.

Can I provide array size dynamically?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.


1 Answers

I think the answers you are looking for are rbind() and cbind():

> x=NULL  #  could also use x <- c()

> rbind(x, c(1,2))
     [,1] [,2]
[1,]    1    2
> x <- rbind(x, c(1,2))
> x <- rbind(x, c(1,2))  # now extend row-wise
> x
     [,1] [,2]
[1,]    1    2
[2,]    1    2
> x <- cbind(x, c(1,2))  # or column-wise
> x
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    1    2    2

The strategy of trying to assign to "new indices" on the fly as you attempted can be done in some languages but cannot be done that way in R.

You can also use sparse matrices provided in the Matrix package. They would allow assignments of the form M <- sparseMatrix(i=200, j=50, x=234) resulting in a single value at row 200, column 50 and 0's everywhere else.

 require(Matrix)
 M <- sparseMatrix(i=200, j=50, x=234)
 M[1,1]
#   [1] 0
 M[200, 50]
#   [1] 234

But I think the use of sparse matrices is best reserved for later use after mastering regular matrices.

like image 71
IRTFM Avatar answered Sep 21 '22 13:09

IRTFM