【问题标题】:Write a function that return string of passed objects编写一个返回传递对象字符串的函数
【发布时间】:2023-02-02 20:36:15
【问题描述】:

我想用一个参数“object”创建一个名为“test”的 R 函数,它可以是数据框或数据框列表:

  • 如果对象是数据框,test() 必须以字符串形式返回数据框的名称
  • 如果对象是一个列表,test() 必须返回一个字符串向量,其中每个元素都是数据帧的名称。

我希望 test() 与管道 %>% 和 |> 一起工作。

我试过的:

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

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

不幸的是,在我的测试中,它给出了这个:

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

【问题讨论】:

    标签: r


    【解决方案1】:

    dplyr

    library(dplyr)
    
    test <- function(object) {
      if (class(object) == "data.frame") {
        return(deparse(substitute(object)))
      } else if (class(object) == "list") {
        return(lapply(object, function(x) deparse(substitute(x))))
      } else {
        stop("Input must be a data frame or a list of data frames.")
      }
    }
    
    # must return "iris"
    iris %>% test()
    # must return c("iris", "mtcars")
    list(iris, mtcars) %>% test()
    

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      相关资源
      最近更新 更多