Siddharth Gosalia
Siddharth Gosalia

Reputation: 311

Reorganize data frame in R

I have a data frame in R which is as follows:

A <- c(7,2,7)
B <- c(1,8,4)
C <- c(9,4,3)
Category <- c("A","B","C")

df <- data.frame(Category, A, B, C)

The data frame looks like this:

  Category | A | B | C
 -----------------------
     A       7   1   9
     B       2   8   4
     C       7   4   3

How can I reorganize the data frame in r to get the below output?

Category | Category | Value
---------------------------
    A         A         7    
    A         B         1
    A         C         9
    B         A         2
    B         B         8
    B         C         4
    C         A         7
    C         B         4
    C         C         3

Upvotes: 0

Views: 2353

Answers (2)

Kerry Jackson
Kerry Jackson

Reputation: 1871

One way you can do this is using the tidverse by gathering the data and then after it is gathered renaming a column to have two columns with the same name.

library(tidyr)
library(dplyr)

df %>% 
  gather(Category2, Value, -Category) %>% 
  arrange(Category, Category2) %>% 
  rename(Category=Category2)

Upvotes: 3

akrun
akrun

Reputation: 886938

An easier option would be to transpose the dataset without the first column, then change the column name to 'Category' values and convert to data.frame after giving the table attribute

as.data.frame.table(`colnames<-`(t(df[-1]), df$Category))[c(2, 1, 3)]
#   Var2 Var1 Freq
#1    A    A    7
#2    A    B    1
#3    A    C    9
#4    B    A    2
#5    B    B    8
#6    B    C    4
#7    C    A    7
#8    C    B    4
#9    C    C    3

Or using melt after converting to matrix

library(reshape)
melt(as.matrix(`row.names<-`(df[-1], df$Category)))

Upvotes: 2

Related Questions