pv7 pv7 - 28 days ago 13
R Question

Assigning a class to an object from within a function in R

I am trying to assign a class to an object from within a function with no success.

a <- 1
f <- function(x){class(x) <- "first"}
f(a)
class(a)
[1] "numeric"


I do not understand why the assignment does not work. Could you explain me why and tell me how to change the class of an object from within a function? Thank you.

Answer

Try this

a <- 1

f <- function(x){ structure(x, class = "first") }
b <- f(a)
class(b)
[1] "first"

As @Rich was hinting at in the comments, you had not defined a new object, so when you did class(a) it was just going back to your original definition of a, which was numeric (because you never redefined a to be f(a)).

Comments