0

I have melted data that I want to unmelt. I created an "index" column, but I need the column to repeat after each grouped data. Here is an example:

This is what my data looks like:

index start value
1     5     0.4
2     5     0.9
3     5     0.3
4     6     0.2
5     6     0.1
6     6     0.7

and when I unmelt it with dcast it looks like this:

start   1     2     3     4     5      6
5       0.4   0.9   0.3
6                         0.2   0.1    0.7

So I need a way of restarting at "1" when the "start" value changes. So in the end, it looks like this:

start   1     2     3 
5       0.4   0.9   0.3
6       0.2   0.1   0.7

Thanks!

Shree
  • 10,835
  • 1
  • 14
  • 36
Dane Kania
  • 45
  • 7
  • `rep(1:3, length(unique(df$start)))`? – iod Nov 17 '18 at 01:01
  • Possible duplicate of [Transpose / reshape dataframe without “timevar” from long to wide format](https://stackoverflow.com/questions/11322801/transpose-reshape-dataframe-without-timevar-from-long-to-wide-format) – Henrik Nov 17 '18 at 10:22

2 Answers2

2

Here is one way to create the appropriate index column assuming df is your dataframe object -

df$index <- ave(df$start, df$start, FUN = seq_along)
Shree
  • 10,835
  • 1
  • 14
  • 36
1

With dplyr:

group_by(df, start) %>%
  mutate(index=row_number())
iod
  • 7,412
  • 2
  • 17
  • 36