Fill missing values
nafill.Rd
Fast 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 or integer, value to be used to fill.
- nan
(numeric
x
only) EitherNaN
orNA
; if the former,NaN
is treated as distinct fromNA
, otherwise, they are treated the same during replacement?- 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
dt = data.table(v1=x, v2=shift(x)/2, v3=shift(x, -1L)/2)
nafill(dt, "nocb")
#> $v1
#> [1] 3 3 3 4 7 7 7 8 NA NA
#>
#> $v2
#> [1] 1.5 1.5 1.5 1.5 2.0 3.5 3.5 3.5 4.0 NA
#>
#> $v3
#> [1] 1.5 1.5 2.0 3.5 3.5 3.5 4.0 NA NA NA
#>
setnafill(dt, "locf", cols=c("v2","v3"))
dt
#> v1 v2 v3
#> <int> <num> <num>
#> 1: NA NA NA
#> 2: NA NA 1.5
#> 3: 3 NA 2.0
#> 4: 4 1.5 2.0
#> 5: NA 2.0 2.0
#> 6: NA 2.0 3.5
#> 7: 7 2.0 4.0
#> 8: 8 3.5 4.0
#> 9: NA 4.0 4.0
#> 10: NA 4.0 4.0