Fill missing values
nafill.RdFast fill missing values using constant value, last observation carried forward or next observation carried backward.
Arguments
- x
Vector, list, data.frame or data.table of numeric columns.
- type
Character, one of "const", "locf" or "nocb". Defaults to
"const".- fill
Numeric value to be used to replace missing observations. See examples.
- nan
Either
NaNorNA; if the former,NaNis treated as distinct fromNA, otherwise, they are treated the same during replacement. See Examples.- cols
Numeric or character vector specifying columns to be updated.
Details
Only double and integer data types are currently supported.
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.
Examples
x = 1:10
x[c(1:2, 5:6, 9:10)] = NA
nafill(x, "locf")
#> [1] NA NA 3 4 4 4 7 8 8 8
x = c(1, NA, NaN, 3, NaN, NA, 4)
nafill(x, "locf")
#> [1] 1 1 1 3 3 3 4
nafill(x, "locf", nan=NaN)
#> [1] 1 1 NaN 3 NaN NaN 4
# fill= applies to any leftover NA
nafill(c(NA, x), "locf")
#> [1] NA 1 1 1 3 3 3 4
nafill(c(NA, x), "locf", fill=0)
#> [1] 0 1 1 1 3 3 3 4
dt = data.table(v1=x, v2=shift(x)/2, v3=shift(x, -1L)/2)
nafill(dt, "nocb")
#> $v1
#> [1] 1 3 3 3 4 4 4
#>
#> $v2
#> [1] 0.5 0.5 1.5 1.5 1.5 NA NA
#>
#> $v3
#> [1] 1.5 1.5 1.5 2.0 2.0 2.0 NA
#>
setnafill(dt, "locf", cols=c("v2","v3"))
dt
#> v1 v2 v3
#> <num> <num> <num>
#> 1: 1 NA NA
#> 2: NA 0.5 NA
#> 3: NaN 0.5 1.5
#> 4: 3 0.5 1.5
#> 5: NaN 1.5 1.5
#> 6: NA 1.5 2.0
#> 7: 4 1.5 2.0