[R] concatenating column names in a loop

Joshua Wiley jwiley.psych at gmail.com
Mon Jul 19 22:26:16 CEST 2010


"so I must use a loop."  is almost never true in R.  This works:

colnames(y) <- paste("q_", colnames(x), sep = "")

HTH,

Josh

On Mon, Jul 19, 2010 at 12:35 PM, Josh B <joshb41 at yahoo.com> wrote:
> Hi all,
>
> I am trying to concatenate words together to create new column names, using a
> loop.
>
> Please consider the following toy example:
>
> x <- matrix(nrow = 1, ncol = 3)
> colnames(x) <- c("a", "b", "c")
> x[1,1] <- "1"
> x[1,2] <- "2"
> x[1,3] <- "3"
>
> I would like to create a new matrix with column names based on the column names
> in x. Specifically, I would like the column names in y to be "q_" plus the
> corresponding column name in x. So y[,1] should be named "q_a", y[,2] should be
> names "q_b", and y[,3] should be named "q_c".
>
>
> Here is the code I am trying:
>
> y <- matrix(nrow = nrow(x), ncol = ncol(x))
> for (i in 1:ncol(x)){
>    colnames(y)[i] <- paste("q_", (colnames(x)[i]), sep = "")
> }
>
> Alas, it does not work. I get the following error (from the console window):
>
> Error in dimnames(x) <- dn :
>  length of 'dimnames' [2] not equal to array extent
>
>
> Can any of you help to debug my code? Please consider the following constraints:
> (1) In reality, my dataset has many more than three columns, so I must use a
> loop.
> (2) I would like my code to be robust against changes in the column numbers of
> the x matrix. That is why I am telling R to look up the number of rows and
> columns in the x matrix when constructing the y matrix, rather than just putting
> in a hard count for the number of rows and columns in the y matrix.
>
>
> Thanks in advance,
> Josh Banta
>
>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list