Reputation: 507
I couldn't find anything about how to do this. I want to perform a set of analyses in R within a separate environment. For example:
n.e <- new.env()
n.e$df <- mtcars[mtcars$cyl == 6,]
n.e$avg_mpg <- mean(n.e$df$mpg)
n.e$median_qsec <- median(n.e$df$qsec)
The actual calculations aren't important, but the crux is that it's cumbersome starting everything with n.e$
. If there were some way to work exclusively in the environment n.e
, such as:
n.e <- new.env()
workwithinenvironment(n.e){
df <- mtcars[mtcars$cyl == 6,]
avg_mpg <- mean(df$mpg)
median_qsec <- median(df$qsec)
}
Which would end with the same result, but I could do without writing n.e$
over and over again.
Upvotes: 2
Views: 66
Reputation: 162321
One possibility is to use with()
, which (as noted on its help page) will accept an environment as its first argument.
n.e <- new.env()
with(n.e, {
df <- mtcars[mtcars$cyl == 6,]
avg_mpg <- mean(df$mpg)
median_qsec <- median(df$qsec)
})
## Check that it works
ls(n.e)
## [1] "avg_mpg" "df" "median_qsec"
n.e$avg_mpg
## [1] 19.74286
Upvotes: 3