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:
- You hvae a missing closing bracket in your function.
- You probably want to do an if else combination.
- 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"