Louis GRIMALDI
Louis GRIMALDI

Reputation: 101

Melting dataframe in R

I have the following R dataframe :

foo <- data.frame("Department" = c('IT', 'IT', 'Sales'),
                  "Name.boy" = c('John', 'Mark', 'Louis'), 
                  "Age.boy" = c(21,23,44), 
                  "Name.girl" = c('Jane', 'Charlotte', 'Denise'), 
                  "Age.girl" = c(16,25,32))

which looks like the following :

    
Department Name.boy Age.boy Name.girl Age.girl
IT         John     21      Jane      16
IT         Mark     23      Charlotte 25
Sales      Louis    44      Denise    32

How do I 'melt' the dataframe, so that for a given Department, I have three columns : Name, Age, and Sex ?

Department Name       Age   Sex
IT         John       21    Boy
IT         Jane       16    Girl
IT         Mark       23    Boy
IT         Charlotte  25    Girl
Sales      Louis      44    Boy
Sales      Denise     32    Girl

Upvotes: 0

Views: 85

Answers (2)

Edward
Edward

Reputation: 18739

Using reshape:

reshape(foo, direction="long", varying=2:5, tiemvar="Sex")

       Department  Sex      Name Age id
1.boy          IT  boy      John  21  1
2.boy          IT  boy      Mark  23  2
3.boy       Sales  boy     Louis  44  3
1.girl         IT girl      Jane  16  1
2.girl         IT girl Charlotte  25  2
3.girl      Sales girl    Denise  32  3

Upvotes: 2

akrun
akrun

Reputation: 887168

We can use pivot_longer from tidyr

library(tidyr)
pivot_longer(foo, cols = -Department, names_to = c(".value", "Sex"), 
   names_sep="\\.")
# A tibble: 6 x 4
#  Department Sex   Name        Age
#  <chr>      <chr> <chr>     <dbl>
#1 IT         boy   John         21
#2 IT         girl  Jane         16
#3 IT         boy   Mark         23
#4 IT         girl  Charlotte    25
#5 Sales      boy   Louis        44
#6 Sales      girl  Denise       32

Upvotes: 3

Related Questions