This may be a trivial question, but I am struggling to address it. I am trying to index a named variable in a function. Take the following example. I would like to assign labels to my variables. I know I can do this with the following lines of code
iris<–iris
attr(iris$Sepal.Width, "label") <- "Label 1"
library(Hmisc)
contents(iris)
Labels Levels Storage
Sepal.Length double
Sepal.Width Label 1 double # my variable is labelled
Petal.Length double
Petal.Width double
Species 3 integer
However, if I try to create a function that does the same operation, I incur into an error because I am unable to index named variables in user-written functions.
For instance, if I create a function labvar
thus defined i incur into an error.
labvar <- function(var,lab){
attr(iris[[var]], "label") <- lab
}
labvar("Sepal.Length", "label 2")
Labels Levels Storage
Sepal.Length double # variable remains not labelled
Sepal.Width Label 1 double
Petal.Length double
Petal.Width double
Species 3 integer
I have also tied multiple alternatives to index the variable with iris[[var]]
,iris[var]
,iris{{var}}
but none of these approach work.
Can anyone help me and explain how I can index a named variable as I would do with $
outside the function?
thanks a lot in advance for your help