Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pivot to get row and column names as rows along with values in R

I have a dataset which looks like below and i want to flatten it.

inp <- matrix(c(0,1,0,0,2,3,5,0,4,3,6,0),nrow = 4, byrow = T)
rownames(inp)<- c("A","B","C","D")
colnames(inp) <-c("x","y","z")

Expected Output:

A y 1
B y 2
B z 3
C x 5
C z 4
D x 3
D y 6

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Regarding inp as a table, convert it to a data frame and remove zero rows. Omit the last line if the order of rows is unimportant. No packages are used.

d <- subset(as.data.frame.table(inp), Freq > 0)
d[order(d$Var1), ]

giving:

   Var1 Var2 Freq
5     A    y    1
6     B    y    2
10    B    z    3
3     C    x    5
11    C    z    4
4     D    x    3
8     D    y    6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading