'How does the overloading of the assignment operator in combination of the length function work?
How does the mutating implementation of length()
actually work?
Example: Given a vector v
, how does this set the length to 12?
length(v) <- 12
Can I create my own function that can overload an operator in the same way?
Example: Set every other element to 7
everyOther(v) <- 7
Solution 1:[1]
Those assignment functions are just that, functions. They can be written in the following form (note the backticks - they must be used), where fname
distinguishes the function name.
`fname<-` <- function(x, value) { ... }
So your everyOther
assignment function can be written as
`everyOther<-` <- function(x, value) {
x[c(FALSE, TRUE)] <- value
x
}
And we can use it just as we would length(x) <- value
v <- 1:20
everyOther(v) <- 7
v
# [1] 1 7 3 7 5 7 7 7 9 7 11 7 13 7 15 7 17 7 19 7
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |