Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I have a data frame that looks like this.

x a 1 

x b 2 

x c 3 

y a 3 

y b 3 

y c 2 

I want this in matrix form so I can feed it to heatmap to make a plot. The result should look something like:

    a    b    c

x   1    2    3

y   3    3    2

I have tried cast from the reshape package and I have tried writing a manual function to do this but I do not seem to be able to get it right.

1 Answer

0 votes
by
edited by

To reshape columns from a data frame from a long to wide format matrix, you can use the spread function from the tidyverse package as follows:

df <- data.frame(x=gl(2,3, labels=letters[24:25]),

                  y=gl(3,1,6, labels=letters[1:3]), 

                  z=c(1,2,3,3,3,2))

 head(df)

  x y z

1 x a 1

2 x b 2

3 x c 3

4 y a 3

5 y b 3

6 y c 2

library(tidyr)

spread(df, y, z)

  x a b c

1 x 1 2 3

2 y 3 3 2

To convert to a matrix:

M <- as.matrix(sapply(df,as.numeric))

class(M)

[1] "matrix"

M

     x a b c

[1,] 1 1 2 3

[2,] 2 3 3 2

You can also use the reshape function from the base package as follows:

reshape(df, idvar = "x", timevar = "y", direction = "wide")

  x z.a z.b z.c

1 x   1   2   3

4 y   3   3   2

To convert to a matrix:

M <- as.matrix(sapply(df,as.numeric))

class(M)

[1] "matrix"

M

     x z.a z.b z.c

[1,] 1   1   2   3

[2,] 2   3   3   2

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...