0
votes

I need help transforming a long df to a wide one.

I think this is a basic questions, but I'm stucked.

After reading about ´reshape2´, I've used this:

dcast(a,  day + sessions ~ hour)

And all possible variations.

But didn't get the expected result.

This is my starting data frame "a":

head(a)

  day  hour  sessions
1 Sun    0      785
2 Sun    1      354
3 Sun    2      190
4 Sun    3      121
5 Sun    4      105
6 Sun    5      110

Expected result: I need to have this format:

  day    0       1    2    3     ... 23
1 Sun    123    454   23   43    ... 56
2 Mon    56     354   778  76    ....89
3 Thur   75     190   653  533   ....87
4 Wen    3      121   45    54   ....77
5 Tue    4      105   21   44    ....52
6 Fri    5      110   12   21    ....51

str of df "a":

'data.frame':   168 obs. of  3 variables:
 $ day     : Ord.factor w/ 7 levels "Sun"<"Mon"<"Tues"<..: 1 1 1 1 1 1 1 1 1 1 ...
 $ hour    : Factor w/ 24 levels " 0"," 1"," 2",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ sessions: num  785 354 190 121 105 110 185 258 252 416 ...
1
care to elaborate a bit more about the error you getMLavoie
Try dcast(a, day ~ hour)ialm
When you post sample data, you should make an effort to construct a sample answer that does not contradict that data. This surely a question that has an answer on SO. You should also post some record of the effort you put into searching.IRTFM

1 Answers

1
votes

As @ialm mentioned in the comments, this is easily done by using the reshape2 package.

I don't know what your dataframe really looks like since your example is a little weird, but:

library(reshape2)

a <- data.frame(
day = c('Sun', 'Sun', 'Mon', 'Mon'), 
hour = c(1, 2, 1, 2),
sessions = c(354, 190, 121, 105))

dcast(a, day ~ hour)

...should give you

  day   1   2
1 Mon 121 105
2 Sun 354 190