问题
Background
- I would like to evaluate a set of R function with a package environment without attaching this package
- I would like to avoid using
package::
Example
Data
Given sample dummy data set:
# Data --------------------------------------------------------------------
tmpCSV <- tempfile(fileext = ".CSV", pattern = "mtcars_data_")
write.csv(x = mtcars[, 1:5], file = tmpCSV, row.names = FALSE)
# Confirm
# readLines(con = tmpCSV)[1]
Reading
library
I could read it with use of read_csv function offered within the readr package.
library(readr)
dta <- read_csv(
file = tmpCSV,
col_types = cols(
mpg = col_double(),
cyl = col_integer(),
disp = col_integer(),
hp = col_integer(),
drat = col_double()
)
)
readr::
It would be also possible to call readr::
functions directly:
# detach("package:readr", unload=TRUE)
dta <- readr::read_csv(
file = tmpCSV,
col_types = readr::cols(
mpg = readr::col_double(),
cyl = readr::col_integer(),
disp = readr::col_integer(),
hp = readr::col_integer(),
drat = readr::col_double()
)
)
Problem
I would like to arrive at the same results using eval/evalq
(if possible). Desired syntax would resemble:
eval(expr = read_csv(
file = tmpCSV,
col_types = cols(
mpg = col_double(),
cyl = col_integer(),
disp = col_integer(),
hp = col_integer(),
drat = col_double()
)
),
# Naturally, the "" bit does not make sense
envir = "package::readr")
Expected error:
Error in
read_csv(file = tmpCSV, col_types = cols(mpg = col_double(),
: could not find function"read_csv"
Notes
The task is mostly concerned with accessing package functions without loading package and without calling functions directly via ::
and :::
. Conceptual equivalent would be using with
function and referring to data frame columns without $
:
with(mtcars, t.test(disp ~ am))
better example:
with(mtcars, mpg[cyl == 8 & disp > 350])
回答1:
Just use with
? I don't understand why you don't want to use ::
.
setwd("E:/temp")
tmpCSV <- tempfile(fileext = ".CSV", pattern = "mtcars_data_")
write.csv(x = mtcars[, 1:5], file = tmpCSV, row.names = FALSE)
dta <- readr::read_csv(
file = tmpCSV,
col_types = readr::cols(
mpg = readr::col_double(),
cyl = readr::col_integer(),
disp = readr::col_integer(),
hp = readr::col_integer(),
drat = readr::col_double()
)
)
sessionInfo()
#attached base packages:
# [1] stats graphics grDevices datasets utils methods base
#loaded via a namespace (and not attached):
#[1] readr_1.1.1 compiler_3.4.4 assertthat_0.2.0 R6_2.2.2 cli_1.0.0
#[6] hms_0.4.2 tools_3.4.4 pillar_1.2.1 rstudioapi_0.7 tibble_1.4.2
#[11] crayon_1.3.4 Rcpp_0.12.16 utf8_1.1.3 pkgconfig_2.0.1 rlang_0.2.0
#[16] fortunes_1.5-4
dtb <- with(asNamespace("readr"), read_csv(
file = tmpCSV,
col_types = cols(
mpg = col_double(),
cyl = col_integer(),
disp = col_integer(),
hp = col_integer(),
drat = col_double()
)))
#same happens here
identical(dta, dtb)
#[1] TRUE
来源:https://stackoverflow.com/questions/49852970/evaluate-function-within-package-environment-without-attaching-package