transpose matrix R

2019-02-15 05:55发布

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

4条回答
一夜七次
2楼-- · 2019-02-15 06:46

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)
查看更多
欢心
3楼-- · 2019-02-15 06:51

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
查看更多
在下西门庆
4楼-- · 2019-02-15 06:54

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

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-15 06:58

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
查看更多
登录 后发表回答