[R] Differencing between 2 previous values

peter dalgaard pdalgd at gmail.com
Mon Jul 28 11:44:06 CEST 2014


On 28 Jul 2014, at 11:08 , Pavneet Arora <pavneet.arora at uk.rsagroup.com> wrote:

> Hello All,
> 
> I am trying to do a simple thing of calculating the absolute difference 
> between 2 previous values. Since my original data consists of 30 rows, 
> this column where I am storing my absolute difference values only consists 
> of 29 rows (called the ?differ?)! And I am having troubling cbind ing the 
> 2 columns. Is there any way I can make the first  row of ?differ? column 
> as NA?
> 
> So my data looks like following
> dput(data)
> tructure(list(week = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
> 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 
> 29, 30), value = c(9.45, 7.99, 9.29, 11.66, 12.16, 10.18, 8.04, 
> 11.46, 9.2, 10.34, 9.03, 11.47, 10.51, 9.4, 10.08, 9.37, 10.62, 
> 10.31, 10, 13, 10.9, 9.33, 12.29, 11.5, 10.6, 11.08, 10.38, 11.62, 
> 11.31, 10.52)), .Names = c("week", "value"), row.names = c(NA, 
> -30L), class = "data.frame")
> 
> This is how I calculate my ?diff? column:
> differ <- abs(diff(data$value))
> Which gives me the following results:
> [1] 1.46 1.30 2.37 0.50 1.98 2.14 3.42 2.26 1.14 1.31 2.44 0.96
> [13] 1.11 0.68 0.71 1.25 0.31 0.31 3.00 2.10 1.57 2.96 0.79 0.90
> [25] 0.48 0.70 1.24 0.31 0.79
> 
> As you can see this only contains 29 rows, so when I try to cbind it to my 
> current data, I have an error. 
> cbind(differ,data)
> Error in data.frame(..., check.names = FALSE) : 
>  arguments imply differing number of rows: 29, 30
> 
> What I ideally want is my new dataset to look as:
> Week            Value           Differ
>   1              9.45             NA
>   2              7.99            1.46
>   3              9.29            1.30
> 
> And so on?.

The straightforward way is 

data$Differ <- c(NA, abs(diff(data$value)))

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list