create a check if variable have values to skip codes

I am trying to create a check if value is assigned then execute code other wise the same data frame:

for eg if column name of data frame is assigned values

df6 <- data.frame(name=c("try,xab","xab,Lan","mhy,mun","vgtu,mmc","dgsy,aaf","kull,nnhu","hula,njam","mund,jiha","htfy,ntha","bhr,gydbt","sgyu,hytb","vdti,kula","mftyu,huta","ibdy,vcge","cday,bhsue","ajtu,nudj"),
                  email=c("xab.try@ybcd.com","Lan.xab@ybcd.com","tth.vgu@ybcd.com","mmc.vgtu@ybcd.com","aaf.dgsy@partnt.com","nnhu.kull@ybcd.com","njam.hula@ybcd.com","jiha.mund@ybcd.com","ntha.htfy@ybcd.com","gydbt.bhr@ybcd.com","hytb.sgyu@ybcd.com","kula.vdti@ybcd.com","huta.mftyu@ybcd.com","ggat.khul@ybcd.com","bhsue.cday@ybcd.com","nudj.ajtu@ybcd.com"))

BB=TRUE
col_drop <- c("partnt.com")
df6 <- mutate(df6, email = if_else(BB==TRUE & grepl(col_drop, email), email, NULL)) # skip this line if BB= FALSE or BB= ""

I just want to skip the step if BB = False

just a solution to skip any check if var = "" or var not provided

Hi,

If I understand you correctly, all you need is a simple if-statement

# skip this line if BB= FALSE or BB= ""
if(BB){
  df6 <- mutate(df6, email = if_else(
                  BB==TRUE & grepl(col_drop, email),
                  email, NULL))
  
}

In this case if BB = TRUE the line will run, if BB is FALSE it wont.

You can also create logic with variables other than boolean (TRUE/FALSE) like this

if(var != ""){
 # code to run when var is NOT ""
}

if(is.na(var)){
 # code to run when var is NA. Use is.null() for NULL check
}

if(exists("var"){
 # code to run when var declared
}

Of course you can combine any of these so make more complex checks using and (&) or (|) statements

if(!is.na(var) & var != ""){
 # Run code if var is not NA and not ""
}

Hope this helps,
PJ

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.