[R] How to add a new column to a matrix?
Joshua Wiley
jwiley.psych at gmail.com
Sun Oct 10 06:06:51 CEST 2010
Hi,
This should do it. I tried to comment to explain things.
Z.mat <- matrix(c(2,2,2,1,1,1,3,2,1,6,5,4,9,1,1,2,3,2), nrow=6)
# column bind data together
Z.mat <- cbind(Z.mat, c(6,9,8,15,16,17))
# add names to the 2 dimensions of Z.mat
# the first element of the list is the row names, left as empty
# the second element is the column names
# 'letters' is a built in vector of the lower case letters of
# the Latin alphabet
dimnames(Z.mat) <- list(NULL, letters[1:4])
# Another way would be to use
colnames(Z.mat) <- letters[1:4]
# For documentation see especially
? cbind
? dimnames
Hope that helps,
Josh
On Sat, Oct 9, 2010 at 8:16 PM, Lakshmi Kastury
<skastu01 at students.poly.edu> wrote:
>
> Hi -
> I am a beginner to the R language. I have written the following matrix: Z.mat=matrix(c(2,2,2,1,1,1,3,2,1,6,5,4,9,1,1,2,3,2), nrow=6)
> I would like to add a 4th column consisting of: 6, 9, 8, 15, 16, 17
>
> I would also like to name each column a, b, c, d as well.
>
> Thanks!
>
> [[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