如何在R包中全局使用@importFrom实现批量导入函数?
It sounds like you're missing a few key steps to get @importFrom working properly in your package. Let's walk through what you need to do:
Update your DESCRIPTION file: You have to declare any packages you're importing from in the
Importssection. For example, if you're using functions fromdplyr, add this line to your DESCRIPTION:Imports: dplyrThis tells R that your package depends on these external packages, so they'll be installed alongside yours, and R knows to look for them when loading your code.
Check your roxygen syntax: Make sure your
@importFromtag is inside a valid roxygen comment block (starts with#'). You can put it either at the top of yourpackagename.Rfile (for imports used across multiple functions) or directly above the function that uses the external functions. For example:#' @importFrom dplyr mutate arrange #' @export do_thing <- function(data) { data %>% mutate(new_col = value * 2) %>% arrange(new_col) }The
@exporttag is only necessary if you wantdo_thingto be accessible to users of your package; if you're only calling it within your package (like fromtopic.R), you can skip that line.Regenerate your NAMESPACE file: This is the most likely missing step! Adding
@importFromcomments doesn't automatically update your package's NAMESPACE—you need to run the documentation process to make that happen. In RStudio, go to the Build tab and click Document, or rundevtools::document()in the console. This will scan your roxygen comments and add lines likeimportFrom(dplyr,mutate)to your NAMESPACE, which tells R exactly which functions to pull in from external packages.Reload your package: After updating the NAMESPACE and DESCRIPTION, reload your package using
devtools::load_all()(or click Load All in the Build tab). This ensures all your latest changes are loaded into your R session, so when you calldo_thingfromtopic.R, it can find the imported functions.
If you're still having issues, double-check for typos in the package or function names in your @importFrom tags, and make sure you've installed the external packages you're trying to import from.
内容的提问来源于stack exchange,提问作者wdkrnls

