Search code examples
rdcast

R dataframe reshaping. Column headers need to become values... dcast no avail


I am new to R and I am trying to convert a dataframe that is shaped as

    actor   <- c("a1", "a2", "a3")
    code1 <- c("c1","c2", "c3")
    measure_1 <- c(1, 2, 3)
    measure_2 <- c(4, 5, 6)

    x <- data.frame( actor, player ,measure_1, measure_2, measure_3 )

      actor  code1 measure_1 measure_2 
    1    a1     c1         1         4         
    2    a2     c2         2         5         
    3    a3     c3         3         6         
into 
     actor   code1 meausures   value
    1    a1   c1  measure_1     1      
    2    a1   c1  measure_2     4
    3    a2   c2  measure_1     2
    4    a2   c2  measure_2     5
    5    a3   c3  measure_1     3
    6    a3   c3  measure_2     6

I tried to use, dcast but to no avail. I am not trying to aggregate and use another function to ind mean etc. It is just a reordering of the matrix. But the column headers(measure_1 and measure2) actually become values in the second form and new column headers are assigned.

Thank you for the help in advance.


Solution

  • library(reshape2)
    
    actor   <- c("a1", "a2", "a3")
    code1 <- c("c1","c2", "c3")
    measure_1 <- c(1, 2, 3)
    measure_2 <- c(4, 5, 6)
    
    x <- data.frame( actor, code1 ,measure_1, measure_2)
    
    melt(x, id.vars = c("actor", "code1"),
         variable.name = "measures",
         value.name = "value")