set_attrs()
adds, changes, or zaps attributes of objects. Pass a
single unnamed NULL
argument to zap all attributes. For
uncopyable types, use mut_attrs()
.
set_attrs(.x, ...) mut_attrs(.x, ...)
.x | An object to decorate with attributes. |
---|---|
... | <dynamic> A list of named attributes. Pass
a single unnamed |
set_attrs()
returns a modified shallow copy
of .x
. mut_attrs()
invisibly returns the original .x
modified in place.
Unlike structure()
, these setters have no special handling of
internal attributes names like .Dim
, .Dimnames
or .Names
.
These functions are deprecated since rlang 0.3.0.
set_attrs(letters, names = 1:26, class = "my_chr") #> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #> "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" #> 21 22 23 24 25 26 #> "u" "v" "w" "x" "y" "z" #> attr(,"class") #> [1] "my_chr" # Splice a list of attributes: attrs <- list(attr = "attr", names = 1:26, class = "my_chr") obj <- set_attrs(letters, splice(attrs)) obj #> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #> "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" #> 21 22 23 24 25 26 #> "u" "v" "w" "x" "y" "z" #> attr(,"attr") #> [1] "attr" #> attr(,"class") #> [1] "my_chr" # Zap attributes by passing a single unnamed NULL argument: set_attrs(obj, NULL) #> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" #> [20] "t" "u" "v" "w" "x" "y" "z" set_attrs(obj, !!! list(NULL)) #> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" #> [20] "t" "u" "v" "w" "x" "y" "z" # Note that set_attrs() never modifies objects in place: obj #> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #> "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" #> 21 22 23 24 25 26 #> "u" "v" "w" "x" "y" "z" #> attr(,"attr") #> [1] "attr" #> attr(,"class") #> [1] "my_chr" # For uncopyable types, mut_attrs() lets you modify in place: env <- env() mut_attrs(env, foo = "bar") env #> <environment: 0x560eb02ed318> #> attr(,"foo") #> [1] "bar"