transpose matrix R

2019-02-15 06:08发布

问题:

I have a data frame in R that I want to transpose into a different format, please see the example below: Can I use the transpose function in R?

Input data frame:

Samples          A1    A2      A3     B1     B2       B3

Sample1         123    123     321    32     321       32132 
Sample2         12321  32321   2321   2313   3213      3123  
Sample3         454    54      543    543    43        435

Desired Output:

Samples           1      2       3    

Sample1   A       123    123     321     
Sample1   B       32     321     32132
Sample2   A       12321  32321   2321     
Sample2   B       2313   3213    3123
Sample3   A       454    54      543
Sample3   B       543    43      435

回答1:

To give some props to base R, look at the reshape() function. Assuming your data.frame is called "mydf", try:

reshape(mydf, direction = "long", 
        idvar="Samples", varying=2:ncol(mydf), 
        v.names=c("1", "2", "3"), times = c("A", "B"))
          Samples time     1     2     3
Sample1.A Sample1    A   123   123   321
Sample2.A Sample2    A 12321 32321  2321
Sample3.A Sample3    A   454    54   543
Sample1.B Sample1    B    32   321 32132
Sample2.B Sample2    B  2313  3213  3123
Sample3.B Sample3    B   543    43   435


回答2:

If d is the dataset

Using dplyr

library(dplyr)
library(tidyr)
library(stringr)
 d%>%
 gather(Var, Val,A1:B3) %>%
 mutate(VarN= str_extract(Var,"[A-Z]+"), indx= str_extract(Var, "\\d+")) %>% 
 select(-Var) %>% 
 spread(indx, Val)
  #    Samples VarN   1     2     3
  #1 Sample1    A   123   123   321
  #2 Sample1    B    32   321 32132
  #3 Sample2    A 12321 32321  2321
  #4 Sample2    B  2313  3213  3123
  #5 Sample3    A   454    54   543
  #6 Sample3    B   543    43   435


回答3:

I think you are looking for the package reshape2. It has two functions, melt and dcast that can help you accomplish what you want.

d <- melt(d, id.vars = "Samples")
d$type <- 0
for (i in 1:3) d$type[grep(i, d$variable)] <- i
d$variable <- substr(d$variable, 1, 1)
d <- dcast(d, Samples + variable ~ type)


回答4:

I think you can use t() function to transpose the matrix.