gpt4 book ai didi

r - 加载 R 包时如何分配变量可用?

转载 作者:行者123 更新时间:2023-12-03 20:23:02 25 4
gpt4 key购买 nike

我已经想出了如何制作一个包含一些我经常使用的调色板的包。我修改了this中的代码博客文章以使其正常工作。以下代码是可重现的。
我的具体问题是,这仅在我运行函数时才有效 create_palette()create_palette_list()以下。这些函数目前的结构是使两个对象必须可用于函数 scale_color_mine()scale_fill_mine()上类。所以,我的问题是如何修改包 wlucolors 中的代码以便这些对象在包 wlucolors 的那一刻可用已加载。
我认为这与使全局变量可用于其他一些函数有关,并且可能为全局环境分配了一些东西,但我真的不确定。
感谢您提供任何见解。

remotes::install_github("sjkiss/wlucolors")
library(wlucolors)

library(tidyverse)
create_palette()
create_palette_list()
data("mtcars")
ggplot(mtcars, aes(x = hp, y = mpg, col = cyl)) +
geom_point() +
scale_color_mine(palette = "federal", discrete = F)
df <- data.frame(party = c("lib", "con", "bq", "ndp", "green"),
voteshare = c(12, 15, 15, 16, 18))
ggplot(df, aes(x = party, y = voteshare, fill = party)) +
geom_col() +
scale_fill_mine(palette = "federal", discrete = T)
df <- data.frame(party = c("lib", "con", "bq", "ndp", "green"),
voteshare = c(12, 15, 15, 16, 18))
ggplot(df, aes(x = party, y = voteshare, fill = party)) +
geom_col() +
scale_fill_mine(palette = "federal", discrete = T)

最佳答案

虽然 .onLoad是一种选择,我认为这不是解决此问题的推荐方法(我们可以阅读 here 以了解 .onLoad 的主要用途)。
问题是,你要吗my_colors可供用户使用?或者您只是希望它作为您的函数的内部数据可用。从查看您的 github repo 来看,我认为是后者,但让我们看看这两个选项。他们都在@Waldi 的回答中的上述链接中进行了解释。

  • 使颜色和调色板可用 external data给用户。你可以用 usethis::use_data(my_colors) 来做这件事然后你只需要记录数据,但不要使用 @export在文档中。在描述文件中你可以设置 LazyData: true所以数据只有在实际使用时才会加载到内存中。在这种情况下,您的函数可以使用数据,但用户也可以使用这些数据。
  • 或者,您可以将颜色和调色板设为 internal data为您的功能。这可以使用 {usethis} 中的相同函数来完成,唯一的区别是我们设置了 internal论据 TRUE :usethis::use_data(my_colors, internal = TRUE) .现在您可以在函数内部引用数据 my_palettes并且函数参数可用于子集my_palettes .

  • 例如:
    scale_color_mine(palette = "federal")
    会在内部做:
    scale_color_mine  <- function(palette) {
    # do stuff here
    cur_palette <- my_palettes[[palette]]
    # do stuff here
    }
    在这种情况下,用户将无法访问数据,但好消息是 my_colorsmy_palettes不会填充命名空间。

    关于r - 加载 R 包时如何分配变量可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67353131/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com