firstD: Compute first differences

Description Usage Arguments Details Value Author(s) Examples

View source: R/firstD.R

Description

Compute first differences

Usage

1

Arguments

var

Variable to be first-differenced.

group

Optional grouping variable (see 'Details').

df

Optional data frame containing var and group (see 'Details').

Details

If df is specified then group must also be specified. So it is possible to specify all three parameters, var and group only, or var by itself. An example of when one might wish to omit both group and df is when using firstD in conjunction with plyr's ddply (see 'Examples'). If df is specified then it should be sorted by group and, if necessary, a second variable (e.g. time) that orders the observations of var in the appropriate sequence.

Value

firstD(var) returns a first-differenced version of var. firstD(var,group) returns a first-differenced version of var by group. And firstD(var,group,df) returns a first-differenced version of var by group, where var and group are searched for in df. Note that the first value of firstD(var) will be NA since there is no difference to compute. Similarly, for firstD(var,group) and firstD(var,group,df) the first value for each group will be NA.

Author(s)

Jonah Gabry <jsg2201@columbia.edu>

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Specifying both group and df
df <- data.frame(id = rep(1:3, each = 3), X = rpois(9, 10))
df$Xdiff <- firstD(X, id, df)
df

# Omitting df
id <- rep(1:3, each = 3)
X <- rpois(9, 10)
Xdiff <- firstD(X, id)

# Omitting group and df
## Not run: 
library(plyr)
df <- data.frame(id = rep(1:3, each = 3), X = rpois(9, 10), Y = rpois(9, 5))
ddply(df, "id", mutate, Xdiff = firstD(X), Ydiff = firstD(Y))

## End(Not run)

jgabry/QMSS_package documentation built on May 19, 2019, 7:18 a.m.