How to check whether column is.numeric() inside the function call?

Viewed 126

I am trying to write a small test that will check whether the column supplied is numeric

fun_df <- function(data,x){
   
  if(is.numeric(data$x){
    stop("done!")
  }
  print("did not pass")
}

fun_df(cars, dist)

what will be the best way to specify is.numeric(data$x)? i tried {{x}}, !!x. but I can't get the test pass. I specifically want to specify fun_df(cars, dist) and not fun_df(cars, "dist")

3 Answers

Use deparse(substitute()).

fun_df <- function(data,x) {
  xx <- deparse(substitute(x))
  if(is.numeric(data[[xx]])){
    stop("done!")
  }
  print("did not pass")
}
fun_df(iris, Sepal.Width)

Error in fun_df(iris, Sepal.Width) : done!

Update: see comments:

We do not need substitute: We can use column name only:

fun_df <- function(data,x) {
  
  if(is.numeric(data[,x])){
    stop("done!")
  }
  print("did not pass")
}

fun_df(mtcars, "mpg")
Error in fun_df(mtcars, "mpg") : done!

First answer: Additionally we could use {{}}: (thanks to deschen who solved the bracket issue(+1):

fun_df <- function(data, x) {

 i1 <- data %>%
         pull({{x}}) %>%
     is.numeric
 if(i1)  {
   print("done!") 
 } else
   print("did not pass")    
     
     
  
}

fun_df(cars, dist)
[1] "done!"
  1. You hvae a missing closing bracket in your function.
  2. You probably want to do an if else combination.
  3. If you are open to pass the variable name as a chararcter vector, then the following works:

fun_df <- function(data, x)
{
  if(is.numeric(data[, x]))
  {
    print("done!")
  } else
  print("did not pass")
}

fun_df(mtcars, "mpg")

[1] "done!"
Related