l <- letters
names(l) <- letters
stopifnot({i <- 1:3 ; identical(l[i], l[optimal.index(i, n=length(l))])})
stopifnot({i <- -(4:26) ; identical(l[i], l[optimal.index(i, n=length(l))])})
stopifnot({i <- c(rep(TRUE, 3), rep(FALSE, 23)) ; identical(l[i], l[optimal.index(i, n=length(l))])})
stopifnot({i <- c("a", "b", "c"); identical(l[i], l[optimal.index(i, i.names=names(l))])})
old.options <- options(show.error.messages=FALSE); stopifnot(inherits(try(optimal.index(c(1:3, 3), n=length(l))), "try-error")); options(old.options)
stopifnot({i <- c(1:3, 3, NA);identical(l[i], l[optimal.index(i, n=length(l), strict=FALSE)])})
stopifnot({i <- c(-(4:26), -26);identical(l[i], l[optimal.index(i, n=length(l), strict=FALSE)])})
stopifnot({i <- c(rep(TRUE, 3), rep(FALSE, 23), TRUE, FALSE, NA);identical(l[i], l[optimal.index(i, n=length(l), strict=FALSE)])})
stopifnot({i <- c("a", "b", "c", "a", NA);identical(l[i], l[optimal.index(i, i.names=names(l), strict=FALSE)])})
rm(l)
Run the code above in your browser using DataLab