Last active
December 10, 2023 16:47
-
-
Save hughjonesd/0bbf0440d04fa1e3a967e780c749bafa to your computer and use it in GitHub Desktop.
get back for R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.back_ix <- function (x, ix) { | |
stopifnot(is.numeric(ix), all(abs(ix) <= length(x))) | |
ix <- ix[ix != 0] | |
neg <- ix < 0 | |
ix <- length(x) + 1 - abs(ix) | |
ix[neg] <- -1 * ix[neg] | |
ix | |
} | |
back <- function (x, ix) { | |
x[.back_ix(x, ix)] | |
} | |
`back<-` <- function (x, ix, value) { | |
x[.back_ix(x, ix)] <- value | |
x | |
} | |
letters[length(letters)] # so unreadable | |
letters[(length(letters) - 3):(length(letters))] # even worse | |
letters[length(letters) - 3:0] # still too long | |
tail(letters, 4) # ok | |
tail(letters, 2:4) # boring | |
tail(letters, 1) <- "Z" # boooring | |
rev(letters)[1:3] # ok... | |
rev(letters)[1:3] <- c("Z", "Y", "X") # why can't we have nice things :-( | |
back(letters, 4) | |
back(letters, 1:4) # obviously | |
back(letters, 2:4) # not a problem | |
back(letters, 4:1) # just count from the back | |
back(letters, 4) <- "W" | |
back(letters, 2:3) <- c("Y", "X") | |
letters # as god intended | |
letters[-(1:21)] | |
back(letters, -(1:21)) # of course! | |
letters[0] | |
back(letters, 0) | |
letters[30] | |
back(letters, 30) # don't get over-excited |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment