Skip to content

Instantly share code, notes, and snippets.

@MyKo101
Created April 18, 2021 19:53
Show Gist options
  • Select an option

  • Save MyKo101/4d29713fa0fe91eea887da3b03d5ae70 to your computer and use it in GitHub Desktop.

Select an option

Save MyKo101/4d29713fa0fe91eea887da3b03d5ae70 to your computer and use it in GitHub Desktop.
locks attributes for combination
attribute_lock <- function(x){
if(inherits(x,"attribute_lock")){
x
} else {
ocl <- attr(x,"class")
ncl <- if(!is.null(ocl)) c("attribute_lock",ocl) else "attribute_lock"
structure(x,class=ncl)
}
}
attribute_unlock <- function(x){
structure(x,class=setdiff(attr(x,"class"),"attribute_lock"))
}
print.attribute_lock <- function(x,...){
cat(crayon::green("<attributes locked>\n"))
print(attribute_unlock(x))
}
c.attribute_lock <- function(...){
dots <- list(...)
dots_unlock <- lapply(dots,attribute_unlock)
out <- do.call(c,dots_unlock)
nms <- names(out)
lens <- rep(1:...length(),
vapply(dots_unlock,length,numeric(1)))
for(i in seq_along(dots_unlock)){
names(dots_unlock[[i]]) <- NULL
}
for(i in seq_along(out)){
attributes(out[[i]]) <- attributes(dots_unlock[[lens[i]]])
names(out[[i]]) <- nms[[i]]
}
attribute_lock(out)
}
str.attribute_lock <- function(x,...){
str(attribute_unlock(x))
}
x <- structure(list(x1 = 1), "attr" = 2)
y <- structure(list(y1 = 3), "attr" = 1)
x <- attribute_lock(x)
y <- attribute_lock(y)
res <- c(x,y)
str(res)
z <- structure(list(a=1,b=2),"attr" = 3,"attr2" = c(1,2))
res <- c(x,y,z)
str(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment