reshape - R: How can I make a new Variable with numbers of order (by date) for every level (for reshaping).) -
i´m new r , have deal large data set. googled lot can´t find way need (although sounds easy thing do).
what want reshape data in wide form. in way want, need new variable numbers of order dates every factor (that start 1 each new factor).
now, small example of have:
id<-c("a","a","a","b","b","c","d","d","d","d") date<-c("01-01-2014", "05-01-2014", "06-01-2014", "01-01-2014", "12-01-2014", "25-01-2014", "06-01-2014", "12-01-2014", "25-01-2014", "26-01-2014") value<-c(2.5, 3.4, 2.5, 305.66, 300.00, 55.01, 205.32, 99.99, 210.25, 105.125) mydata<-data.frame(id, date, value) mydata id date value 1 01-01-2014 2.500 2 05-01-2014 3.400 3 06-01-2014 2.500 4 b 01-01-2014 305.660 5 b 12-01-2014 300.000 6 c 25-01-2014 55.010 7 d 06-01-2014 205.320 8 d 12-01-2014 99.990 9 d 25-01-2014 210.250 10 d 26-01-2014 105.125
(data set sorted first id factor, date each factor.)
and need: new variable called "order".
id date value order 1 01-01-2014 2.500 1 2 05-01-2014 3.400 2 3 06-01-2014 2.500 3 4 b 01-01-2014 305.660 1 5 b 12-01-2014 300.000 2 6 c 25-01-2014 55.010 1 7 d 06-01-2014 205.320 1 8 d 12-01-2014 99.990 2 9 d 25-01-2014 210.250 3 10 d 26-01-2014 105.125 4
the end goal reshape data based on variable "order" this:
library(reshape) goal<-reshape(mydata2, idvar="id", timevar="order", direction="wide") goal id date.1 value.1 date.2 value.2 date.3 value.3 date.4 value.4 1 01-01-2014 2.50 05-01-2014 3.40 06-01-2014 2.50 <na> na 4 b 01-01-2014 305.66 12-01-2014 300.00 <na> na <na> na 6 c 25-01-2014 55.01 <na> na <na> na <na> na 7 d 06-01-2014 205.32 12-01-2014 99.99 25-01-2014 210.25 26-01-2014 105.125
or there way reshape data without "order" variable?
this precisely getanid
function in "splitstackshape" package for:
> library(splitstackshape) > getanid(mydata, "id") id date value .id 1: 01-01-2014 2.500 1 2: 05-01-2014 3.400 2 3: 06-01-2014 2.500 3 4: b 01-01-2014 305.660 1 5: b 12-01-2014 300.000 2 6: c 25-01-2014 55.010 1 7: d 06-01-2014 205.320 1 8: d 12-01-2014 99.990 2 9: d 25-01-2014 210.250 3 10: d 26-01-2014 105.125 4
alternatively, can explore development version of "data.table" reimplements dcast
in flexible way allow transformation without needing generate "time" variable.
Comments
Post a Comment