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

Time:11-03

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")

CodePudding user response:

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!

CodePudding user response:

  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!"

CodePudding user response:

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

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

fun_df(cars, "mpg")
[1] "did not pass"
  •  Tags:  
  • r
  • Related