Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using attr function dynamically

Considering the following data frame

df<-data.frame(a=c(1,2,3))

I can show it by doing:

df

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

get("df")

Also, I can give an attribute to it by doing this:

attr(df,"anyAttribute")<-"df attribute"
attributes(df)
$names
[1] "a"

$class
[1] "data.frame"

$row.names
[1] 1 2 3

$anyAttribute
[1] "df attribute"

Is there any way to give attributes to dataframes dynamically?. What I want is something like this:

> attr(get("df"),"anyAttribute")<-"df attribute"
Error in attr(get("df"), "anyAttribute") <- "df attribute" : 
  destino de la asignación se expande a un objeto fuera del lenguaje

>Solution :

We can use assign to update the original object

tmp <- get('df')
attr(tmp, 'anyAttribute') <- 'df attribute'
assign('df', tmp)

-output

> str(df)
'data.frame':   3 obs. of  1 variable:
 $ a: num  1 2 3
 - attr(*, "anyAttribute")= chr "df attribute"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading