shift_by {quest} | R Documentation |
Shift a Vector (i.e., lag/lead) by Group
Description
shift_by
shifts elements of a vector right (n
< 0) for lags or
left (n
> 0) for leads by group, replacing the undefined data with a
user-defined value (e.g., NA). The number of elements shifted is equal to
abs(n)
. It is assumed that x
is already sorted within each
group by time such that the first element for that group is earliest in time
and the last element for that group is the latest in time.
Usage
shift_by(x, grp, n, undefined = NA)
Arguments
x |
atomic vector or list vector. |
grp |
list of atomic vector(s) and/or factor(s) (e.g., data.frame),
which each have same length as |
n |
integer vector with length 1. Specifies the direction and magnitude of the shift. See details. |
undefined |
atomic vector with length 1 (probably makes sense to be the
same typeof as |
Details
If n
is negative, then shift_by
inserts undefined
into the
first abs(n)
elements of x
for each group, shifting all other
values of x
to the right abs(n)
positions, and then dropping
the last abs(n)
elements of x
to preserve the original length
of each group. If n
is positive, then shift_by
drops the first
abs(n)
elements of x
for each group, shifting all other values
of x
left abs(n)
positions, and then inserts undefined
into the last abs(n)
elements of x
to preserve the original
length of each group. If n
is zero, then shift_by
simply returns
x
.
It is recommended to use L
when specifying n
to prevent
problems with floating point numbers. shift_by
tries to circumvent this
issue by a call to round
within shift_by
if n
is not an
integer; however that is not a complete fail safe. The problem is that
as.integer(n)
implicit in shift_by
truncates rather than rounds.
Value
an atomic vector of the same length as x
that is shifted by
group. If x
and undefined
are different typeofs, then the
return will be coerced to the most complex typeof (i.e., complex to simple:
character, double, integer, logical).
See Also
Examples
shift_by(x = ChickWeight[["Time"]], grp = ChickWeight[["Chick"]], n = -1L)
tmp_nm <- c("vs","am") # b/c Roxygen2 doesn't like c() in a []
shift_by(x = mtcars[["disp"]], grp = mtcars[tmp_nm], n = 1L)
tmp_nm <- c("Type","Treatment") # b/c Roxygen2 doesn't like c() in a []
shift_by(x = as.data.frame(CO2)[["uptake"]], grp = as.data.frame(CO2)[tmp_nm],
n = 2L) # multiple grouping vectors