Search code examples
rdataframemelt

Transform a dataframe to use first column values as column names


I have a dataframe with 2 columns:

  .id vals
1   A   10
2   B   20
3   C   30
4   A  100
5   B  200
6   C  300

dput(tst_df)
structure(list(.id = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("A", 
"B", "C"), class = "factor"), vals = c(10, 20, 30, 100, 200, 
300)), .Names = c(".id", "vals"), row.names = c(NA, -6L), class = "data.frame")

Now i want to have the .id column to become my column names and the vals will become 2 rows.

Like this:

A    B    C
10   20   30
100  200  300

Basically .id is my grouping variable and i want to have all values belonging to 1 group as a row. I expected something simple like melt and transform. But after many tries i still not succeeded. Is anyone familiar with a function that will accomplish this?


Solution

  • You can do this in base R with unstack:

    unstack(df, form=vals~.id)
        A   B   C
    1  10  20  30
    2 100 200 300
    

    The first argument is the name of the data.frame and the second is a formula which determines the unstacked structure.