NA
)na-rle.Rd
Compute the lengths and indices of runs of NA
in a vector – or the reverse
operation.
na_rle(x = double(), index_by = seq_along(x), interval = NULL) list_of_na_rle(x = double(), index_by = seq_along(x), interval = NULL) na_rle_inverse(x) na_rle_lengths(x) na_rle_starts(x) na_rle_ends(x)
x | A vector. |
---|---|
index_by | A vector of the same length as |
interval | if |
An object of class rle_na
or list_of_rle_na
. A named list of:
lengths
: the lengths of NA
runs
indices
: the starting indices of runs
Many math operations can be applied to objects returned from na_rle()
and
list_of_na_rle()
, regarding the lengths of runs.
library(dplyr, warn.conflicts = FALSE) df <- tibble(year = 2000:2019, temp = sample(0:30, size = 20)) df[c(1, 6, 13:16, 19), "temp"] <- NA df#> # A tibble: 20 x 2 #> year temp #> <int> <int> #> 1 2000 NA #> 2 2001 22 #> 3 2002 11 #> 4 2003 4 #> 5 2004 5 #> 6 2005 NA #> 7 2006 25 #> 8 2007 3 #> 9 2008 26 #> 10 2009 8 #> 11 2010 27 #> 12 2011 20 #> 13 2012 NA #> 14 2013 NA #> 15 2014 NA #> 16 2015 NA #> 17 2016 6 #> 18 2017 10 #> 19 2018 NA #> 20 2019 19na_rle(df$temp) # indexed by the default positions#> <Run Length Encoding <NA>[4]> #> $lengths: <int> 1 1 4 1 #> $indices: <int> 1 6 13 19(x <- na_rle(df$temp, index_by = df$year)) # indexed by a variable#> <Run Length Encoding <NA>[4]> #> $lengths: <int> 1 1 4 1 #> $indices: <int> 2000 2005 2012 2018# getters na_rle_inverse(x)#> [1] 2000 2005 2012 2013 2014 2015 2018na_rle_lengths(x)#> [1] 1 1 4 1na_rle_starts(x)#> [1] 2000 2005 2012 2018na_rle_ends(x)#> [1] 2000 2005 2015 2018# subsetting x[1:2]#> <Run Length Encoding <NA>[2]> #> $lengths: <int> 1 1 #> $indices: <int> 2000 2005#> [1] 4#> [1] 7#> [1] 1 4# list_of_na_rle() is useful when working with tabular data na_rle_df <- df %>% mutate(group = rep(letters[1:2], each = 10)) %>% group_by(group) %>% summarise(na_runs = list_of_na_rle(temp, year)) na_rle_df#> # A tibble: 2 x 2 #> group na_runs #> <chr> <list<rle<NA>>> #> 1 a [2] #> 2 b [2]na_rle_inverse(na_rle_df$na_runs)#> [[1]] #> [1] 2000 2005 #> #> [[2]] #> [1] 2012 2013 2014 2015 2018 #>#> [1] 2 5#> <list_of<integer>[2]> #> [[1]] #> [1] 1 1 #> #> [[2]] #> [1] 1 4 #>