Josh B 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))
Does...
colnames(y) <- paste("q_", colnames(x), sep = "")
work?
<snip>
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.
Not true! R has many functions like colnames that are vectorized, i.e.,
operate on vectors of arbitrary length, making for-loops unnecessary!
______________________________________________
R-help@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.