Span <- function(f, x)
{
## Purpose: A Predicate Functional that finds the location of the longest sequential run
## of elements where the predicate is true.
## Arguments:
## f: a predicate (a function that returns a single TRUE or FALSE)
## x: a list or data frame
## Return: The location of the longest sequential run of elements where the predicate is true.
## Author: Feiming Chen, Date: 28 Jun 2017, 09:45
## ________________________________________________
y <- rle(Where(f, x))
z <- y$lengths
w <- which.max(z) # position of the segment with longest sequential run of TRUE
pos.end <- sum(z[1:w])
pos.start <- pos.end - z[w] + 1
c(start=pos.start, end=pos.end)
}
if (F) { # Unit Test
x <- c(3, 1, NA, 4, NA, NA, NA, 5, 9, NA, NA)
Span(is.na, x)
## start end
## 5 7
}
Where <- function(f, x)
{
## Purpose: A Predicate Functional
## See other Predicate Functionals: Filter(), Find(), Position()
## See other Functionals: Map(), Reduce()
## Arguments:
## f: a predicate (a function that returns a single TRUE or FALSE) (e.g. is.character, all, is.NULL)
## x: a list or data frame
## Return: a logical vector
## Author: Feiming Chen, Date: 28 Jun 2017, 09:45
## ________________________________________________
vapply(x, f, logical(1))
}
if (F) { # Unit Test
df <- data.frame(x = 1:3, y = c("a", "b", "c"), stringsAsFactors = T)
Where(is.factor, df)
## Compare with:
Filter(is.factor, df)
Find(is.factor, df)
Position(is.factor, df)
}
Wednesday, June 28, 2017
Span: A Predicate Functional that finds the location of the longest sequential run of elements where the predicate is true
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment