1

I have this data.frame:

> head(ir_dfSTORED)
         ind   m
1 2015-12-15  21
2 2015-12-15  42
3 2015-12-15  63
4 2015-12-15  84
5 2015-12-15 105
6 2015-12-15 126
> tail(ir_dfSTORED)
           ind    m
835 2015-12-21 2415
836 2015-12-21 2436
837 2015-12-21 2457
838 2015-12-21 2478
839 2015-12-21 2499
840 2015-12-21 2520

The "ind" column has the dates repeated by 120 rows, i have 7 dates. 120 x 7 = 840 rows.

The "m" column gives me 120 numbers (21, 42, 63, 84, 105, 126,...,2520) for each day. A vector of 120 number for each day.

I want to convert each number of "m" column, from 21 to 2520, as a new column (120 columns).

My final data.frame should have the "ind" column as the first one. And then, the second column should be "21", the third "42", ..., 120th column should be "2520".

After this a would like to have in the "ind" column non repeated dates, only the seven dates (seven rows). Here i know that i can use the unique command. I believe its not a big problem. But i cant do the convertion of "m" column.

So, i would have a data frame with 121 columns and 7 rows.

How can i do this?

jogo
  • 12,469
  • 11
  • 37
  • 42
  • 1
    I feel like this may be a job for the package `reshape2` and the function `melt`. I'm sure others will correct me if I'm wrong but that is a place to start. `Melt` may not be correct but there should be something in `reshape2` that can help you. – Badger Dec 23 '15 at 15:03
  • 1
    @Badger, probably you meant `dcast` – Marat Talipov Dec 23 '15 at 15:04
  • 1
    Possible duplicate of [Reshape data from long to wide format R](http://stackoverflow.com/questions/5890584/reshape-data-from-long-to-wide-format-r) – jogo Dec 23 '15 at 17:02

2 Answers2

3

Reshape2 will serve your purposes with the function dcast.

dcast(df,ind ~ m)

The formula effectively states ind following m and will achieve the result of each day being a single row with the respective columns flowing out from each. Props to @MaratTalipov for the correction.

Badger
  • 1,043
  • 10
  • 25
1

Here is a solution with reshape() from base R:

ir_dfSTORED$time <- ave(ir_dfSTORED$m, ir_dfSTORED$ind, FUN=seq_along)
reshape(ir_dfSTORED, dir="wide", idvar="ind")
jogo
  • 12,469
  • 11
  • 37
  • 42