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
>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