Home > OS >  How to pass on variable names (i.e. var_x) OR transformation of variables (i.e. as.factor(var_x)) in
How to pass on variable names (i.e. var_x) OR transformation of variables (i.e. as.factor(var_x)) in

Time:11-11

In ggplot we can easily put in variable names of dataframes in our code, i.e.

df <- data.frame(a=1:10, b= 1:10, c= 1:10)
ggplot(df, aes(a, b, col= c))   geom_point()

or we can transform the variables right inside the code, i.e. here we change the colour variable c to a factor:

ggplot(df, aes(a, b, col= as.factor(c)))   geom_point()

I want my function to do the same. So if my function is

my_fun <- function(data, var){
  var <- deparse(substitute(var))
  class(data[ , var])
}

I want my_fun(df, a) to return numeric and, on the other hand, my_fun(df, as.factor(a)) must return factor. How can we achieve this?

CodePudding user response:

Try any of these.

my_fun1 <- function(data, x) eval(substitute(x), data)

my_fun2 <- function(data, ...) with(data, ...)

my_fun3 <- with

e.g. (and similarly for the others)

my_fun1(BOD, Time) # returns numeric object
## [1] 1 2 3 4 5 7

my_fun1(BOD, factor(Time))  # returns factor object
## [1] 1 2 3 4 5 7
## Levels: 1 2 3 4 5 7
  • Related