So I basically want to create a 'property' in R which I haven't really found documentation or other SO Q/A explaining how this works.
So an example of what I'm looking for to make a function property
with the behavior found in some base R functions (eg dim(), names(), attr(), etc...), where you can do property(variable) = value
and then have property(variable) == value
be true.
I was hoping that this would work:
x = 1
property = function(x) attr(x, 'property')
`property<-` = function(x, value) attr(x, 'property') <<- value
property(x) = 2
property(x)
But it didn't and in hindsight I have no idea how I would do this since x is copied by value.
You may use `attr<-`
in your function.
x <- 1
property <- function(x) attr(x, 'property')
`property<-` <- function(x, value) `attr<-`(x, 'property', value)
property(x) <- 2
property(x)
# [1] 2
Or, using your code, you need to do return(x)
after assigning something to it.
`property<-` <- function(x, value) {attr(x, 'property') <- value;x}
property(v) <- 2
property(v)
# [1] 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.