如果在功能未检测到列内停止

时间:2015-10-07 09:16:34

标签: r

我编写了一个函数,如果某个列没有被识别为日期格式,该函数应该停止,我已经实现了这个:

if(is.Date(dataname[,datename]) !=TRUE) { stop("Please format the date column as a date column")}

但是在功能中,这给了我一个错误:

func1 <-function(dataname,datename){ ... }

func1(dataname,"date")


 Error in .subset(x, j) : invalid subscript type 'closure' 

表示未检测到日期列。

然而,当我在一个函数之外尝试它时,它可以完美地运行:

 if(is.Date(dataname[,"date"]) !=TRUE) { print("Please format the date column as a date column")}
 if(is.Date(dataname[,"date"]) !=FALSE) { print("Please format the date column as a date column")}
 "Please format the date column as a date column"

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:3)

试试这个:

func1 <- function(df, col){

  if( !is(df[, col], "Date") ){
    stop("Please format the date column as a date column") 
  } else {
    "all good"  
  }
}

#dummy data
data <- data.frame(date = as.Date(c("2010-12-31", "2010-11-01")),
                   x = 1:2)

#testing
func1(data, "date")
# [1] "all good"

func1(data, "x")
# Error in func1(data, "x") : 
#   Please format the date column as a date column