1

I have a data frame that consists of the following columns (simplified): Date, ID, Price:

 Date           ID      Price  
1/2/2013    05947U4Q8   25  
1/2/2013    05947UT40   9.40264  
1/2/2013    07387BAW3   8.75  
1/2/2013    07387BBJ1   4.4861  
1/2/2013    07387BEQ2   5  
1/2/2013    12513EAY0   6  
1/2/2013    20047PAS6   33  
1/3/2013    05947UT40   9.40414  
1/3/2013    07387BAW3   8.75  
1/3/2013    07387BBJ1   4.4742  
1/3/2013    07387BEQ2   5  
1/3/2013    12513EAY0   6  
1/3/2013    20047PAS6   33  

So, for every Date, there are several IDs, with a single Price for each. The IDs may change from one day to the next (some dropping off, others being added). What I'm trying to compute is, for every day, the change in price for every ID (if ID's price was known the previous day). So, for the example above, the output should be:

  Date          ID  Price change  
1/3/2013    05947UT40   0.0015  
1/3/2013    07387BAW3   0  
1/3/2013    07387BBJ1   -0.0119  
1/3/2013    07387BEQ2   0  
1/3/2013    12513EAY0   0  
1/3/2013    20047PAS6   0  

Naively using:

tapply(dataSet$Price, as.Date(dataSet$Date), diff)

does not work, i.e. does not give me what I'm looking for.

2
  • Side note: your data are not really "multidimensional" . Each type of data is a vector here (one column). Commented Oct 25, 2013 at 15:16
  • Can you guarantee there's at most one entry per day for a given item? If so, the problem gets easier. Commented Oct 25, 2013 at 15:17

1 Answer 1

1
dt <- data.table(dt)
setkey(dt,ID,Date)
dt[,pricediff:= Price - c(NA,head(Price,-1)), by = ID][!is.na(pricediff)]

I'm assuming Date is stored as a datetype, not some weirdly ordered factor or character. If so, then this should work. Try having records for the same ID for "11/10/2013" and "11/9/2013" and storing it as a character to see the problem of storing it as a character.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.