0

I have simple R code as follows:

change <- function(x, v) {
  attr(x, 'abc') <- v
  attributes(x)
}

change(iris$Sepal.Length, 't1')
attributes(iris$Sepal.Length)

the result shows:

> change(iris$Sepal.Length, 't1')
$abc
[1] "t1"

> attributes(iris$Sepal.Length)
NULL

as you can see, attributes(x) printed inside the function shows x (which is iris$Sepal.Length) has the attribute abc as t1. but after function is called, attributes(iris$Sepal.Length) shows 'abc' is not defined anymore.

Anyone knows why? How can I change object's attribute inside a function using passed arguments?

Charles Wu
  • 16
  • 2
  • 1
    Heck, even changes to the value of an object would be lost with that sort of code. R IS A FUNCTIONAL LANGUAGE. Why am I shouting? Because you are using logic from experiences with a procedural language. Instead, you need to understand that changes to an object inside a function body do not affect the value of that object outside UNLESS you assign the changes to the original name. Your code should be renamed `change_inside_but_not_yet_real`. Furthermore to change the attributes, use `attributes(iris$Sepal.Length) – IRTFM Mar 02 '22 at 04:53
  • I was trying to change attribute by parameters, as I have a bunch of attributes of an object to change, instead of writing them line by line, I was trying to put the attribute name in a list, then lapply() to change them in one line. Any way to do that? – Charles Wu Mar 08 '22 at 09:30
  • There is an attr – IRTFM Mar 08 '22 at 09:35

0 Answers0