如何将函数转换为管道友好函数?

How to convert a function into pipe-friendly functions?

我正在尝试将以下函数转换为管道友好函数。但它是由字符串组成的。我不知道从哪里开始。

library(MplusAutomation)

pathmodel <- mplusObject(
   TITLE = "MplusAutomation Example - Path Model;",
   MODEL = "
     mpg ON hp;
     wt by disp drat;",
   OUTPUT = "CINTERVAL;",
   rdata = mtcars)

我尝试过这种格式,但我不确定哪种格式不起作用,我也不确定如何创建它以便它与管道一起使用。

mplus <- function(data, title, on, by, output) {
  mplusObject(TITLE = as.character(title),
              MODEL = paste(on, "/n", by),
              OUTPUT = as.character(output),
              rdata = data)
  
}

这就是我最终要实现的目标。

mplus %>%
  data(mtcars) %>%
  title("example - path model") %>%
  predictors("mpg on hp") %>%
  latentvars("wt by disp drat") %>%
  output(cinterval)

您可以通过以下方式使此函数动态化:

mplus <- function(data, title, on, by, output) {
  mplusObject(TITLE = title,
              MODEL = paste(on, "/n", by),
              OUTPUT = output,
              rdata = data)
}

然后将其命名为:

mtcars %>%
  mplus("example - path model", "mpg on hp", "wt by disp drat", "CINTERVAL")

如果你想拥有管道功能,那么你需要一个管道对象。这里我们只是将值存储在列表中。像

new_mplus <- function(data=NA) {
  x <- list(TITLE=NA, MODEL=NA, OUTPUT=NA, predictors=NA, latent=NA, rdata=data)
  class(x) <- "mplus"
  x
}

is_mplus <- function(x) {
  "mplus" %in% class(x)
}

mplus <- function(data) {
  stopifnot(is.data.frame(data))
  new_mplus(data)
}

title <- function(x, title) {
  stopifnot(is_mplus(x))
  x$TITLE <- title
  x
}

predictors <- function(x, predictors) {
  stopifnot(is_mplus(x))
  x$predictors <- predictors
  x
}

latentvars <- function(x, latent) {
  stopifnot(is_mplus(x))
  x$latent <- latent
  x
}

output <- function(x, output) {
  stopifnot(is_mplus(x))
  x$OUTOUT <- output
  x
}

然后你用

调用它
mtcars %>%
  mplus() %>%
  title("example - path model") %>%
  predictors("mpg on hp") %>%
  latentvars("wt by disp drat") %>%
  output("cinterval")

该列表将记录您的所有价值观。然后你只需要有一个函数来执行它

execute <- function(x) {
  mplusObject(TITLE = x$TITLE
              MODEL = paste(x$predictors, "/n", x$latent),
              OUTPUT = x$OUTPUT,
              rdata = x$data)
}

mtcars %>%
  mplus() %>%
  title("example - path model") %>%
  predictors("mpg on hp") %>%
  latentvars("wt by disp drat") %>%
  output("cinterval") %>% 
  execute()

管道都是关于将对象从一个函数传递到下一个函数,因此您需要传递某种对象来存储所有值。使用 dplyr 您将传递一个 tibble 而使用 ggplot2 您将创建一个 ggplot 对象。