[R] rbind/cbind

David Winsemius dwinsemius at comcast.net
Wed Aug 10 15:50:25 CEST 2011


On Aug 10, 2011, at 9:08 AM, Anthony Ching Ho Ng wrote:

> Dear list,
>
> I wonder if there a better way to have rbind/cbind/append to create
> the first element (if it is empty) instead of doing the following in a
> loop?
>
> for (i in 1:10) {
>  if (i == 1) {
>     aRow = SomeExpression(i)
>  } else {
>    aRow = rbind(aRow,SomeExpression(i))
>  }
> }
>

Generally one is advised not to use rbind in this manner but rather to  
pre-allocate aRow to the size needed and then to add information by  
rows using "[".

For a matrix this might be:

aRow <- matrix(NA, ncol=3, nrow=10)

for (i in 1:10) {
     aRow[1,] <- SomeExpression(i)
  }


-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list