Home > Software engineering >  Write a function that return string of passed objects
Write a function that return string of passed objects

Time:02-03

I would like to create an R function called "test" with a single argument "object" which can be either a data frame or a list of data frames :

  • if object is a data frame, test() must return the name of the data frame as a string
  • if object is a list, test() must return a vector of strings where each element is the name of the data frames.

I would like test() to work with pipes %>% and |>.

What I tried :

test <- function(object) {
  return(deparse(substitute(object)))
}

# must return "iris"
iris |> test()
# must return "iris" "mtcars"
list(iris,mtcars) |> test()

Unfortunately with my test, it gives this :

> list(iris,mtcars) |> essai()
[1] "list(iris, mtcars)"

CodePudding user response:

test <- function(object) {
  if (class(object) == "list") {
    unlist(lapply(substitute(object), \(x) deparse(x)))[-1]
  } else {
    deparse(substitute(object))
  }
}

iris |> test()
# [1] "iris"

list(iris,mtcars) |> test()
# [1] "iris"   "mtcars"

CodePudding user response:

Updated code:

test <- function(object) {
  if (class(object) == "data.frame") {
    return(deparse(substitute(object)))
  } else if (class(object) == "list") {
    return(unlist(lapply(object, function(x) deparse(substitute(x)))))
  } else {
    stop("Input must be a data frame or a list of data frames.")
  }
}

# must return "iris"
test(iris)
# must return c("iris", "mtcars")
test(list(iris, mtcars))

      
  •  Tags:  
  • r
  • Related