mardi 22 juin 2021

How do you put an if () {} else {} statement in an R function

I am having trouble, as I am writing a command in r, such as:

Command <- function (df1, var1) {
NewDF1 <- df1 %>% filter(value <= var1)
}

but then when I add a if () {} else {} statement to the code, it ends the function when it runs into the first } of the if else statement and just starts running the remaining code in the function ....

Command <- function (df1, var1) {
     if(var1>5) {
         NewDF1 <- df1 %>% filter(value <= var1)
         NewDF2 <- df1 %>% filter(value = var1)
         return(NewDF1, NewDF2)
         } else {
         NA
         }
     return(df1)
}

Also, because the action if conditions are met consists of 2 commands, I think I am unable to use ifelse() or is there a way to pass 2 actions into ifelse(), for example:

ifelse(var1>5, NewDF1 <- df1 %>% filter(value <= var1) **and** NewDF2 <- df1 %>% filter(value = var1), NA )

Aucun commentaire:

Enregistrer un commentaire