0

I have a two column of data in which first column is a ID and second as a value. For example

ID  Value
1   0.5
2   30
3   20
4   11
5   21
6   12
1   15
2   18
3   19
4   10
5   14
6   1
1   6
2   30
3   2.5
4   3
5   45
6   5

I want to split this column into

ID  Value   value1  value2
1   0.5 15  6
2   30  18  30
3   20  19  2.5
4   11  10  3
5   21  14  45
6   12  1   5

So far I have the following codes but I don't know how to split them.

data=data.table(trial.csv, header=T, sep=",")
dframe=data.frame(data)
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Lira
  • 53
  • 2
  • 9
  • The term used to refer to this operation is "reshape". There is a `reshape` function an then there are a variety of packages that support efforts to make this easier to acheive. Do some searching in SO for "[r] reshape long wide", and while you are at it learn to capitalize "i" when it refers to you and using the appropriate formatting functions in SO's interface. – IRTFM Nov 16 '15 at 04:33

1 Answers1

0

We can use data.table. We convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'ID', we create a sequence column ('ind') and then dcast from 'long' to 'wide' format

library(data.table)#v1.9.6+
setDT(df1)[, ind:= 1:.N, ID]
dcast(df1, ID~paste0('value', ind), value.var='Value')
#   ID value1 value2 value3
#1:  1    0.5     15    6.0
#2:  2   30.0     18   30.0
#3:  3   20.0     19    2.5
#4:  4   11.0     10    3.0
#5:  5   21.0     14   45.0
#6:  6   12.0      1    5.0
akrun
  • 874,273
  • 37
  • 540
  • 662