首页 > 解决方案 > 如何检查函数调用中的列 is.numeric() 是否?

问题描述

我正在尝试编写一个小测试来检查提供的列是否为数字

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

fun_df(cars, dist)

指定的最佳方法是is.numeric(data$x)什么?我试过了{{x}}!!x。但我无法通过测试。我特别想指定fun_df(cars, dist)而不是fun_df(cars, "dist")

标签: r

解决方案


使用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!

推荐阅读