[R] Adding columns to a 2D vector

Sarah Goslee sarah.goslee at gmail.com
Wed Jun 3 16:03:18 CEST 2015


Hi,

On Wed, Jun 3, 2015 at 8:26 AM, Thomas Chesney
<Thomas.Chesney at nottingham.ac.uk> wrote:
> I'd like to add some columns into the middle of this:
>
> vec <- c(1, -1)
> lst <- lapply(numeric(n-1), function(x) vec)
> combos <- as.matrix(expand.grid(lst))
> colnames(combos) <- NULL

This isn't quite reproducible, since n is undefined. I substituted
numeric(6), since that gives the right number of columns.

I'd take advantage of R's habit (bug or feature? your call!) of
repeating items as needed:
combos2 <- cbind(0, combos[, 1:3], 0, combos[, 4:6], 0)


> The way I have used is:
>
> combos2 <- matrix(NA, nrow=64, ncol=9)
> combos2[,1] <- 0
> combos2[,2] <- combos[,1]
> combos2[,3] <- combos[,2]
> combos2[,4] <- combos[,3]
> combos2[,5] <- 0
> combos2[,6] <- combos[,4]
> combos2[,7] <- combos[,5]
> combos2[,8] <- combos[,6]
> combos2[,9] <- 0
>
> But I guess there is an easier way - is there a way to simply insert new columns into combos?
>
> BTW I know I could have shortened this a bit to:
>
> combos2[,2:4] <- combos[,1:3]
>
> ==========
>
> Also can anyone recommend a good source to explain my combos data type? I don't fully understand all the output of this:
>
> str(combos)
>  num [1:64, 1:6] 1 -1 1 -1 1 -1 1 -1 1 -1 ...
>  - attr(*, "dimnames")=List of 2
>   ..$ : NULL
>   ..$ : NULL

Well, take a careful look.
The first line tells you that your matrix is numeric (matrices can
only contain elements of one type), that it has 64 rows and 6 columns,
and a bit of what the contents look like.
The second line tells you that your matrix has as attributes a list of
two dimnames, and the subsequent lines tell you that both row and
column names are NULL (because you set them that way!)

Try, for example, str(data.frame(combos)) and compare. Working through
the examples in ?str might also help.

Sarah


> Thank you,
>
> Thomas Chesney
>
>
>



More information about the R-help mailing list