簡體   English   中英

R package中如何包含顯示圖片?

[英]How to include and display images in R package?

我正在嘗試 package 一個 Shiny 模塊,它顯示帶有徽標的模態(png 格式)。 為此,我創建了一個“inst/www”目錄來存儲徽標文件。 目錄樹看起來像這樣:

├─ DESCRIPTION
├─ inst
│   └── www
│       └── logo.png
├── man
│   └── test.Rd
├── NAMESPACE
├── packagetest.Rproj
└── R
    └── test.R

然而,在構建和安裝之后,package 似乎沒有從我放置“logo.png”的預定義目錄中讀取。 相反,它從我從 package 插入 function 的主項目中讀取。package 的 testUI() function 是這樣的:

testUI <- function(id) {
  ns <- NS(id)

  shiny::showModal(
    modalDialog(
      title = img(src="inst/www/logo.png", style="display:block; margin-left:auto; margin-right:auto;"),
      br(),
      fluidRow(
        column(6, align="center", offset = 3,
               textInput(ns("username"), label = NULL, placeholder = "Username"),
               passwordInput(ns("password"), label = NULL, placeholder = "Password")
        )
      ),
      footer = (
        fluidRow(
          column(6, align="center", offset = 3,
                 actionButton(ns("signin"),"Sign in")
          )
        )
      )
    )
  )
}

從我在其他項目中看到的情況來看,“inst”文件夾似乎是通往 go 的途徑,但我對 R 包還是陌生的,所以我真的不知道自己在做什么。 非常感謝對此的任何幫助,謝謝!

...差不多一年后,我在處理需要包含圖像資產的實際 package 時找到了問題的答案! 根據關於 inst 文件夾的官方 R package 文檔部分:

要從代碼中查找 inst/ 中的文件,請使用 system.file()。 例如,要查找 inst/extdata/mydata.csv,您需要調用 system.file("extdata", "mydata.csv", package = "mypackage")。 請注意,您從路徑中省略了 inst/ 目錄。 如果安裝了 package,或者如果它已使用 devtools::load_all() 加載,這將起作用。

在這種情況下,假設我的 package 被稱為“testpackage”:

testUI <- function(id) {
  ns <- NS(id)

  shiny::showModal(
    modalDialog(
      title = img(
                src=system.file("www/logo.png", package = "testpackage"),
                style="display:block; margin-left:auto; margin-right:auto;"
      ),
      br(),
      fluidRow(
        column(6, align="center", offset = 3,
               textInput(ns("username"), label = NULL, placeholder = "Username"),
               passwordInput(ns("password"), label = NULL, placeholder = "Password")
        )
      ),
      footer = (
        fluidRow(
          column(6, align="center", offset = 3,
                 actionButton(ns("signin"),"Sign in")
          )
        )
      )
    )
  )
}

請注意,我沒有使用官方示例中所示的逗號分隔目錄結構,因為我發現輸入完整的相對路徑更直觀,請記住:

安裝 package 時,inst/ 中的所有內容都會復制到頂級 package 目錄中。 在某種意義上,inst/ 與 .Rbuildignore 相反 - 其中 .Rbuildignore 允許您從頂層刪除任意文件和目錄,inst/ 允許您添加它們。 您可以隨意將任何您喜歡的內容放入 inst/ 中,但要注意一點:因為 inst/ 被復制到頂級目錄中,所以您永遠不應該使用與現有目錄同名的子目錄。 這意味着您應該避免使用 inst/build、inst/data、inst/demo、inst/exec、inst/help、inst/html、inst/inst、inst/libs、inst/Meta、inst/man、inst/po、 inst/R、inst/src、inst/tests、inst/tools 和 inst/vi.nettes。

希望這可以幫助其他面臨同樣問題的人:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM