Equivalent of “throw” in R

后端 未结 5 1144
有刺的猬
有刺的猬 2020-12-07 12:09

How does one \"throw\" an error in R? I have a function that takes a data frame and some column names and does stuff with them. If the columns don\'t exist, I want the fun

5条回答
  •  太阳男子
    2020-12-07 12:37

    You can check if the column exists and do whatever your want.
    Suppose a data.frame named df1 and checking if column col1 exists:

    if(! any(grepl('^col1$',colnames(df1)))) stop("nonexistent column")
    

    or

    if(! any(grepl('^col1$',colnames(df1)))) return(-1)
    

    For instance

提交回复
热议问题