| nafill {data.table} | R Documentation |
Fill missing values
Description
Fast fill missing values using constant value, last observation carried forward or next observation carried backward.
Usage
nafill(x, type=c("const", "locf", "nocb"), fill=NA, nan=NA)
setnafill(x, type=c("const", "locf", "nocb"), fill=NA, nan=NA, cols=seq_along(x))
Arguments
x |
Vector, list, data.frame or data.table of logical, numeric or character columns. |
type |
Character, one of "const", "locf" or "nocb". Defaults to |
fill |
Value to be used to replace missing observations. See examples. |
nan |
Either |
cols |
Numeric or character vector specifying columns to be updated. |
Details
Supported types are logical, integer, double, character, and factor, as well as classes built on top of these such as Date, IDate, and POSIXct.
Note that both nafill and setnafill provide some verbose output when getOption('datatable.verbose') is TRUE.
Value
A list except when the input is a vector in which case a vector is returned. For setnafill the input argument is returned, updated by reference.
See Also
Examples
x = 1:10
x[c(1:2, 5:6, 9:10)] = NA
nafill(x, "locf")
x = c(1, NA, NaN, 3, NaN, NA, 4)
nafill(x, "locf")
nafill(x, "locf", nan=NaN)
# works for factors
x = gl(3, 2, 10)
is.na(x) = 1:2
nafill(x, "nocb")
# fill= applies to any leftover NA
nafill(c(NA, x), "locf")
nafill(c(NA, x), "locf", fill=0)
dt = data.table(v1=x, v2=shift(x)/2, v3=shift(x, -1L)/2)
nafill(dt, "nocb")
setnafill(dt, "locf", cols=c("v2","v3"))
dt