[R] question about transpose

Joshua Wiley jwiley.psych at gmail.com
Sat Jan 30 09:28:54 CET 2010


Hello,

Here are three examples.  I have a hunch you are looking for the last one.


> test <- matrix(LETTERS[1:6], nrow=2, dimnames=list(c("First", "Second"))) #explicitly stating what the rownames are before transposing
> test
       [,1] [,2] [,3]
First  "A"  "C"  "E"
Second "B"  "D"  "F"
> t(test)
     First Second
[1,] "A"   "B"
[2,] "C"   "D"
[3,] "E"   "F"


> test2 <- matrix(LETTERS[1:6], nrow=2)
> dimnames(test2) <- list(c(test2[,1])) # another option if you really want the names to be whatever is in the first column
> test2
  [,1] [,2] [,3]
A "A"  "C"  "E"
B "B"  "D"  "F"
> t(test2)
     A   B
[1,] "A" "B"
[2,] "C" "D"
[3,] "E" "F"


## My guess is that you are looking for this one.  What was in the
first column in the original matrix, is removed from the transposed
matrix and used as the column names
## "[,-1]" indicates everything but column 1
## ncol has to be specified because I used matrix() so I could include dimnames
## dimnames are set to be the contents of the first column of the
original matrix
> test3 <- matrix(letters[1:6], nrow=2)
> test3
     [,1] [,2] [,3]
[1,] "a"  "c"  "e"
[2,] "b"  "d"  "f"
> matrix(t(test3[,-1]), ncol=length(test3[,1]), dimnames=list(NULL,c(test3[,1])))
     a   b
[1,] "c" "d"
[2,] "e" "f"


HTH,


Joshua



On Fri, Jan 29, 2010 at 3:58 PM, Zoppoli, Gabriele (NIH/NCI) [G]
<zoppolig at mail.nih.gov> wrote:
>
> Hi all,
>
> if I transpose a matrix with t(data), the newly created colums do not appear to have the first row as header. How can I do to have all the newly created columns have their first row as a header?
>
> Thanks
>
>
> Gabriele Zoppoli, MD
> Ph.D. Fellow, Experimental and Clinical Oncology and Hematology, University of Genova, Genova, Italy
> Guest Researcher, LMP, NCI, NIH, Bethesda MD
>
> Work: 301-451-8575
> Mobile: 301-204-5642
> Email: zoppolig at mail.nih.gov
> ______________________________________________
> 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
Senior in Psychology
University of California, Riverside
http://www.joshuawiley.com/



More information about the R-help mailing list