Learn R Programming

DataCombine (version 0.2.21)

slideMA: Create a moving average for a period before or after each time point for a given variable

Description

Create a moving average for a period before or after each time point for a given variable

Usage

slideMA(data, Var, GroupVar, periodBound = -3, offset = 1, NewVar, reminder = TRUE)

Arguments

data
a data frame object.
Var
a character string naming the variable you would like to create the lag/lead moving averages from.
GroupVar
a character string naming the variable grouping the units within which Var will be turned into slid moving averages. If GroupVar is missing then the whole variable is slid up or down and moving averages will be created. This is similar to shift, though shift returns the slid data to a new vector rather than the original data frame.
periodBound
integer. The time point for the outer bound of the time period over which to create the moving averages. The default is -3, i.e. the moving average period begins three time points before a given time point. Can also be positive for leading moving averages.
offset
integer. How many time increments away from a given time point to begin the moving average time period. The default is 1. Effectively controls how wide the moving average window is in the other direction of periodBound. Note: must be positive.
NewVar
a character string specifying the name for the new variable to place the slid data in.
reminder
logical. Whether or not to remind you to order your data by the GroupVar and time variable before running slideMA.

Value

a data frame

Details

slideMA is designed to give you more control over the window for creating the moving average. Think of the periodBound and offset arguments working together. If for example, periodBound = -3 and offset = 1 then the variable of interest will be lagged by 2 then a moving average window of three time increments around the lagged variable is found.

See Also

shift, slide, dplyr

Examples

Run this code
 # Create dummy data
 A <- B <- C <- sample(1:20, size = 20, replace = TRUE)
 ID <- sort(rep(seq(1:4), 5))
 Data <- data.frame(ID, A, B, C)

 # Lead the variable by two time units
 DataSlidMA1 <- slideMA(Data, Var = 'A', NewVar = 'ALead_MA',
                 periodBound = 3)

 # Lag the variable one time unit by ID group
 DataSlidMA2 <- slideMA(data = Data, Var = 'B', GroupVar = 'ID',
                NewVar = 'BLag_MA', periodBound = -3, offset = 2)

Run the code above in your browser using DataLab