Search code examples
rfunctionprompt

Overwrite variable inside function


I'm sure this question may have been asked already, but I couldnt find an answer to my satisfaction.

So my Problem I defined a function (See below) which should take a Variable (x) and check if its part of a dataframe (y). The function should than ask for a promt until it is part of said dataframe.

However when I let it run it wont overwrite the variable inside the function so that the global enviroment variable gets also changed. Thus var1 should store the value I gave through the prompt inside the function.

Thx :)

    #Function
    fn_Valid_prompt <- function(x, y, boolOP= FALSE){
       while(is.element(x, colnames(y)) == boolOP){
         cat("A")
         x <<- readline(prompt="Please enter variable: ")
       }
       if (is.element(x, colnames(y)) != boolOP){
              cat(green(bold("Success!")))}
     }

    #
    var1 <- "V1"
    data <- c(1:9)
      metadata <- as.data.frame(matrix(data,3,3))

     fn_Valid_prompt(var1, metadata, boolOP= FALSE)

Solution

  • The following version works, although i'm not sure of your intent with this code :

    #Function
    fn_Valid_prompt <- function(x, y, boolOP= FALSE){
      while(is.element(x, colnames(y)) == boolOP){
        x <- readline(prompt="Please enter variable: ")
      }
      if (is.element(x, colnames(y)) != boolOP){
        cat("Success!")}
      return(x)
    }
    
    #
    var1 <- "V1"
    data <- c(1:9)
    metadata <- as.data.frame(matrix(data,3,3))
    
    result = fn_Valid_prompt("V10", metadata, boolOP= FALSE)
    cat(result)
    

    Your mistake was to use <<- instead of <-. Furthermore, i assume you wanted to return the result ?