mercredi 15 mai 2019

How to get only one iteration in ifelse statement

I am trying to pass a string through a function to call a column from a data frame. I made a very simple if else function to make sure the foundation was working before adding complexity. Essentially if the column name is found within the data frame print Hi, if not print No. The function correctly identifies if the column name is in the data frame but it prints a duplicate No.

I have tried using if(){}else(){}

Using ifelse()

Using break and next with the if(){}else(){} method

df <- as.data.frame(cbind("a" = 1:5,
                    "b" = 6:10))

testingIf <- function(x){
  if(x %in% colnames(df)){
    print("Hi")
  }
  else{
    (print("No"))
  }
}
testingIf("a")
testingIf("This is true")

if(){}else(){} -This was my initial attempt and if the 'if' is true it works as intended and if the 'if' is false it prints out [1] No [1] No.

Using ifelse() -Prints out [1] Hi [1] Hi when true and [1] No [1] No when false

Using break and next with the if(){}else(){} syntax -This works so far as it give me the correct outputs but I get "Error: no loop for break/next, jumping to top level." Which makes me feel like I am missing something.

Aucun commentaire:

Enregistrer un commentaire