项目作者: mdlincoln

项目描述 :
Find Nearest-Neighbor Pathways Through Matrices
高级语言: R
项目地址: git://github.com/mdlincoln/pathway.git
创建时间: 2018-05-27T06:54:21Z
项目社区:https://github.com/mdlincoln/pathway

开源协议:Other

下载


pathway

lifecycle
Travis-CI Build
Status
AppVeyor Build
Status
Coverage
Status

pathway finds a pathway of observations between two points in a matrix.

Installation

You can install pathway from GitHub with:

  1. # install.packages("devtools")
  2. devtools::install_github("mdlincoln/pathway")

Example

  1. library(pathway)
  2. set.seed(34)
  3. m <- matrix(rnorm(1000), nrow = 500, ncol = 2)
  4. p1 <- 2L
  5. p2 <- 11L
  6. p <- pathway(m, p1, p2, n = 5)
  7. # Returns both the ideal points between p1 and p2
  8. p$line
  9. #> [,1] [,2]
  10. #> [1,] 0.9326974 -0.5290643
  11. #> [2,] 0.6655819 -0.3696614
  12. #> [3,] 0.3984664 -0.2102584
  13. #> [4,] 0.1313509 -0.0508555
  14. #> [5,] -0.1357646 0.1085474
  15. # as well as the indices of the nearest neighbors
  16. p$i
  17. #> [1] 227 495 419 479 451
  18. plot_pathway(m, p)

It is also possible to place conditional restraints on the solution that
pathway finds by using navigate_ functions. For example,
navigate_unique will not revisit the same point along a path, and
navigate_ordered will only look at points that occurr in later rows in
the matrix.

  1. p_ordered <- pathway(m, 5, 380, n = 5, navigator = navigate_ordered)
  2. p_ordered$i
  3. #> [1] 75 279 362 367 370
  4. plot_pathway(m, p_ordered)

To use your own predicate function, define a function that returns a
vector of indices to search and call it with navigator = navigate(f)

  1. obs_types <- sample(c("setosa", "versicolor", "virginica"), 500, replace = TRUE)
  2. # A custom predicate function must take the original matrix, the list of
  3. # previously-selected pathway points, along with p1 and p2.
  4. different_species <- function(x, pi, p1, p2, obs_types) {
  5. if (is.null(pi)) {
  6. search_space <- 1:nrow(x)
  7. } else {
  8. # Only search observations that do not have the same species as the immediately previous one.
  9. prev_type <- obs_types[tail(pi, 1)]
  10. search_space <- which(obs_types != prev_type)
  11. }
  12. # Don't forget to exclude p1 and p2
  13. setdiff(search_space, c(p1, p2))
  14. }
  15. p_species <- pathway(m, p1, p2, n = 8, navigator = navigate(different_species, obs_types))
  16. obs_types[p_species$i]
  17. #> [1] "versicolor" "setosa" "virginica" "versicolor" "setosa"
  18. #> [6] "versicolor" "virginica" "setosa"