[datatable-help] seq with data.table

ahardjasa amelia.hardjasa at pulseenergy.com
Mon Jul 21 22:17:30 CEST 2014


marcos.takahashi wrote
> Hi all.
> 
> I am working with a data.table with customer order data, and I have to
> order all orders sequentially by customer, returning the number of that
> order for that customer (eg: order O_10 is the 2nd order of customer A).
> I can do it using some loop statement, but is there a way of doing it on
> another way (maybe using seq)?
> 
> Here's an example of the data:
> 
> DT = data.table(customer=c("A", "A", "B", "B","B","C"),
> order=c(701,325,10,306,289,90))
> 
> Expected result:
> customer order number
> A  325  1
> A  701  2
> B  100  1
> B  289  2
> B  306  3
> C  900  1

You can use order(...) to get the indices in order (ascending by default),
and by to get the indices per each customer.

DT[, number := order(order), by = customer]
setkey(DT, customer, number)



--
View this message in context: http://r.789695.n4.nabble.com/seq-with-data-table-tp4694013p4694323.html
Sent from the datatable-help mailing list archive at Nabble.com.


More information about the datatable-help mailing list