lundi 22 avril 2019

R check if column exists and if it does check something about it

Hi I want to check if a column in a data.frame exists, and only if it does check another conditions.

I know I can use a nested if statement as I have in the example.

This is normally for checking inputs to functions. This is a working example which gives me the output I want, I just was wondering if there is a smarter way, as this can get messy especially if I am doing it for a number of conditions. My example:

testfun <- function(dat,...){
  library(dplyr)
  if("Site" %in% colnames(dat)){
    #for example check number of sites, this condition could be anything though
    if(n_distinct(dat$Site) >  1) stop ("Function must have site specific data")
  }
  #do stuff

  return(1)
}



testdf1 <- data.frame(x = 1:10, y = 1:10)
testdf2 <- data.frame(x = 1:10, y = 1:10,Site = "A")
testdf3 <- data.frame(x = 1:10, y = 1:10,Site = rep(c("A","B"),each = 5))


testfun(testdf1)
testfun(testdf2)
testfun(testdf3)

Aucun commentaire:

Enregistrer un commentaire