Skip to content

Instantly share code, notes, and snippets.

@seasmith
Created July 18, 2019 16:44
Show Gist options
  • Save seasmith/dcaad140df61d54f3c68148d2312233f to your computer and use it in GitHub Desktop.
Save seasmith/dcaad140df61d54f3c68148d2312233f to your computer and use it in GitHub Desktop.
Intuitive vector subsetting using keywords
`[.hmmm` <- function (x, i, ...) {
isub <- substitute(i)
is_seq <- identical(as.list(isub)[[1L]], as.name(":"))
if (is_seq) {
end_seq <- as.list(isub)[[3L]]
is_end <- identical(end_seq, as.name("end"))
if (is_end) {
start <- as.integer(as.list(isub)[[2L]])
end <- length(x)
x <- unclass(x)[start:end]
class(x) <- "hmmm"
x
} else {
x <- unclass(x)[eval(isub)]
class(x) <- "hmmm"
x
}
} else {
x <- unclass(x)[eval(isub)]
class(x) <- "hmmm"
x
}
}
x <- 1:100
class(x) <- "hmmm"
x[99:end]
#> [1] 99 100
#> attr(,"class")
#> [1] "hmmm"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment