Home > Mobile >  How to create this function?
How to create this function?

Time:12-21

I would like to create a verif() function that accepts a single argument called val. This argument can only accept a data frame or a list.
This function should work with the %>% pipe.

This function should return a vector of characters that correspond to the name of the :

  • data frame OR
  • of each element of the list passed before the %>%.

Here's my attempt:

verif <- function(val) {
  if(is.data.frame(val)) {
    return(deparse(substitute(val), backtick = TRUE))
  } else if(is.list(val)) {
    return(sapply(val, function(x) deparse(substitute(x), backtick = TRUE)))
  } else {
    return("Argument must be a data frame or a list.")
  }
}

What I would like:

iris %>% verif() # return "iris"
list(iris, cars) %>% verif() # return c("iris","cars")

Many thanks

CodePudding user response:

This gets you fairly close:

verif <- function(val) {
  if(typeof(val) != 'list') stop('verif must be a list or data frame')
  sc <- sys.calls()
  val <- deparse(substitute(val))
  if(val != '.') return(val)
  
  caller <- sc[[length(sc) - 1]]
  lapply(as.list(caller), deparse)[[2]]
  
}

verif(iris)
#> [1] "iris"

verif(volcano)
#> Error in verif(volcano): verif must be a list or data frame

iris %>% verif()
#> [1] "iris"

list(iris, cars) %>% verif()
#> [1] "list(iris, cars)"

Created on 2022-12-20 with reprex v2.0.2

CodePudding user response:

@allan cameron helps me a lot with his answer and here's what I used :

verif <- function(val) {
  if(typeof(val) != 'list') stop('verif must be a list or data frame')

  sc <- sys.calls()
  caller <- sc[[length(sc) - 1]]
  output_char <- lapply(as.list(caller), deparse)[[2]]
  if (grepl("list",output_char)) {
    # Remove all whitespace from output_char
    output_char <- gsub(" ", "", output_char, fixed = TRUE)
    # Extract string within parenthesis
    matches <- gsub("[\\(\\)]",
                    "",
                    regmatches(output_char,gregexpr("\\(.*?\\)",output_char))[[1]])
    # Separate the elements of the extracted string by a comma
    output <- unlist(strsplit(matches, ","))
  } else {
    output <- output_char
  }

  return(output)

}

iris %>% verif() # returns "iris"
list(iris, cars) %>% verif() # returns "iris" and "cars"


  •  Tags:  
  • r
  • Related