Created
September 26, 2024 22:48
-
-
Save jonocarroll/a22ff6b117c8265c7f845aee54fa1a27 to your computer and use it in GitHub Desktop.
A new vector class that enables a function subsetting assignment method x[f] <- value
This file contains hidden or 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
`[.vec` <- function(x, i, ...) { | |
UseMethod("[.vec", i) | |
} | |
`[<-.vec` <- function(x, i, value, ...) { | |
UseMethod("[<-.vec", i) | |
} | |
`[.vec.default` <- function(x, i, ...) { | |
class(x) <- setdiff(class(x), "vec") | |
x <- x[i] | |
as_vec(x) | |
} | |
`[<-.vec.default` <- function(x, i, value, ...) { | |
class(x) <- setdiff(class(x), "vec") | |
x[i] <- value | |
as_vec(x) | |
} | |
`[.vec.function` <- function(x, f) { | |
class(x) <- setdiff(class(x), "vec") | |
x <- x[f(x)] | |
as_vec(x) | |
} | |
`[<-.vec.function` <- function(x, f, value) { | |
class(x) <- setdiff(class(x), "vec") | |
x[f(x)] <- value | |
as_vec(x) | |
} | |
format.vec <- function(x, ...) { | |
class(x) <- setdiff(class(x), "vec") | |
format(x) | |
} | |
print.vec <- function(x, ...) { | |
class(x) <- setdiff(class(x), "vec") | |
print(x) | |
} | |
iseven <- function(x) { | |
x %% 2 == 0 | |
} | |
as_vec <- function(x) { | |
class(x) <- c("vec", class(x)) | |
x | |
} | |
myvec <- as_vec(1:10) | |
myvec | |
#> [1] 1 2 3 4 5 6 7 8 9 10 | |
myvec[3] | |
#> [1] 3 | |
myvec | |
#> [1] 1 2 3 4 5 6 7 8 9 10 | |
myvec[3] <- 99 | |
myvec | |
#> [1] 1 2 99 4 5 6 7 8 9 10 | |
myvec[iseven] | |
#> [1] 2 4 6 8 10 | |
myvec | |
#> [1] 1 2 99 4 5 6 7 8 9 10 | |
myvec[iseven] <- 0 | |
myvec | |
#> [1] 1 0 99 0 5 0 7 0 9 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment