iLoveCoding
iLoveCoding

Reputation: 21

How can I melt a matrix data frame in R with 2 variables and 1 value column?

My data looks like this:

    col1 col2 col3 
col1 100  25  30  
col2 25  200  50
col3 30  50   300

where the column and row names are c("col1", "col2", "col3")

I want it to look like this:

Var1 Var2 Value
col1 col1 100
col1 col2 25
col1 col3 30
col2 col1 25
col2 col2 200
col2 col3 50
col3 col1 30
col3 col2 50
col3 col3 300

I'm trying reshape2::melt but it's not giving me the results I'm looking for melt(df), any help is appreciated!

Thank you.

Upvotes: 0

Views: 625

Answers (2)

hachiko
hachiko

Reputation: 747

The tidyr package is what you need

library(tidyr)

df <- gather(df, 'Var2', 'Value' 2:4)

Upvotes: 0

akrun
akrun

Reputation: 887118

We can use base R with as.data.frame after creating the attribute for table

as.data.frame.table(m1)
#   Var1 Var2 Freq
#1 col1 col1  100
#2 col2 col1   25
#3 col3 col1   30
#4 col1 col2   25
#5 col2 col2  200
#6 col3 col2   50
#7 col1 col3   30
#8 col2 col3   50
#9 col3 col3  300

data

m1 <- structure(c(100L, 25L, 30L, 25L, 200L, 50L, 30L, 50L, 300L),
.Dim = c(3L, 
3L), .Dimnames = list(c("col1", "col2", "col3"), c("col1", "col2", 
"col3")))

Upvotes: 2

Related Questions