R脚本运行没有问题,但目标管道报错

问题描述 投票:0回答:1

我已经开始使用目标(来自包(目标)),以避免多次重新运行我的分析并使它们更具可重复性。然而,当我运行 run.R 文件(使用 Targets::tar_make())时,在普通 R 脚本中的 R 中运行良好的相同分析会出现错误。 我正在使用本课程中的数据和脚本:https://biostats-r.github.io/biostats/targets/

可以使用以下方式获取数据:

usethis::use_course("biostats-r/targets_workflow_svalbard")

我的 _targets.R 文件如下所示:

# Load packages required to define the pipeline:
library(targets)

# Set target options:
tar_option_set(
  packages = c("tibble", "tidyverse")
)

# Run the R scripts in the R/ folder with your custom functions:
tar_source("R/functions2.R")

# Replace the target list below with your own:
list(
  tar_target(
    name = raw_traits,
    command = "data/PFTC4_Svalbard_2018_Gradient_Traits.csv",
    format = "file"
  ),
  tar_target(
    name = traits,
    command = clean_data(raw_traits)
  ),
  tar_target(
    name = mod_area,
    command = fit_model(data = traits,
                        response = "Value",
                        predictor = "Gradient")
  ),
  tar_target(
    name = fig_area,
    command = make_figure(traits)
  )
)

而myy Functions2.R文件如下:

# clean data
clean_data <- function(raw_traits){
  traits <- raw_traits |>
    filter(!is.na(Value)) |>
    # order factor and rename variable gradient
    mutate(Gradient = case_match(Gradient,
                                 "C" ~ "Control",
                                 "B" ~ "Nutrients"),
           Gradient = factor(Gradient, levels = c("Control", "Nutrients"))) |>
    filter(Taxon == "alopecurus magellanicus",
           Trait == "Leaf_Area_cm2")
}

# run a linear regression
fit_model <- function(data, response, predictor){
  mod <- lm(as.formula(paste(response, "~", predictor)), data = data)
  mod
}

# make figure
make_figure <- function(traits){
  ggplot(traits, aes(x = Gradient, y = Value)) +
    geom_boxplot(fill = c("grey80", "darkgreen")) +
    labs(x = "", y = expression(Leaf~area~cm^2)) +
    theme_bw()
}

当我运行 Targets:tar_make() 时,出现以下错误:

✔ skip target raw_traits
▶ start target traits
✖ error target traits
▶ end pipeline [0.61 seconds]
Error:
! Error running targets::tar_make()
  Error messages: targets::tar_meta(fields = error, complete_only = TRUE)
  Debugging guide: https://books.ropensci.org/targets/debugging.html
  How to ask for help: https://books.ropensci.org/targets/help.html
  Last error: no applicable method for 'filter' applied to an object of class "character"

我尝试过只使用一个函数来使其更简单,但我总是遇到类似的问题。关于问题是什么以及我如何解决它有什么建议吗?我觉得奇怪的是,脚本本身运行良好,但在使用目标时却出现错误。

r filter pipeline target
1个回答
0
投票

我得到了同事的帮助并找到了答案。我写在这里以防有人遇到同样的问题。 我只需要将文件加载为不同的目标即可。定义文件还不够,还需要加载它。代码将如下所示:

list(
  tar_target(
    name = file,
    command = "data/PFTC4_Svalbard_2018_Gradient_Traits.csv",
    format = "file"
  ),
  tar_target(
    name = raw_traits,
    command = read_csv(file)
  tar_target(
    name = traits,
    command = clean_data(raw_traits)
  ),
  ...
© www.soinside.com 2019 - 2024. All rights reserved.