Search code examples
rdataframetranspose

Rearranging R Data Frame


So I got this dataframe here:

> head(HR_df)
  Var1             Var2         Freq
1    A 2432.41955446887 0.0003224956
2    B 2432.41955446887 0.0004902131
3    C 2432.41955446887 0.0002273111
4    D 2432.41955446887 0.0001346622
5    E 2432.41955446887 0.0003125771
6    F 2432.41955446887 0.0004718690

I was trying to make the Var2 column values become all the column names, the Var1 become the row names and the Freq the value. Something like this:

> head(HR_df)
               2432        2501       ....
    A     0.0003224956  0.0004956001  ....
    B     .......         ......      ....

This was supposed to be a simple task, but I'm not very used to R and I can't find an answer anywhere.

Thank you for your time!


Solution

  • Maybe you can try

    reshape(df,direction = "wide",idvar = "Var1",timevar = "Var2")
    

    Example

    Given dummy data

    df <- structure(list(Var1 = c("A", "B", "C"), Var2 = c(0.0286285823676735, 
    0.720798232126981, 0.206408529775217), Freq = c(0.166666666666667,
    0.333333333333333, 0.5)), class = "data.frame", row.names = c(NA,
    -3L))
    

    we will get

    > reshape(df,direction = "wide",idvar = "Var1",timevar = "Var2")
      Var1 Freq.0.0286285823676735 Freq.0.720798232126981 Freq.0.206408529775217
    1    A               0.1666667                     NA                     NA
    2    B                      NA              0.3333333                     NA
    3    C                      NA                     NA                    0.5                  0.5