As my input is frequently in german but I want the code to be pure english I would like to have a short custom dictionary - consisting basically of weekday- and months abbreviations. Thus, I want to create a fast english-german (and vise versa) dictionary - ideally as an environment with parent environment = .GlobalEnv
.
But when I put the code in a function, the dict_g2e
dictionary is not known any more.
set_dict <- function() { # Delete this line and ...
dict_g2e <- new.env(hash = TRUE, size = 7)
from <- c("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa")
to <- c("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat")
for (i in 1:19) {
assign(x = from[i], value = to[i], envir = dict_g2e)
} # this line and the code is working as expected
Test:
> get("So", env = dict_g2e) # ran without the set_dict <- function() {...} part
[1] "Sun"
- Where is the bug?
- I would do the same with
dict_e2g
. Is there a faster & shorter way to do this? - Is there a better command than
get("So", env = dict_g2e)
? Is there any argument againstg2e <- function(wd) {get(wd, envir = dict_g2e)}
Edit after comments from @Roland and @alexis_laz:
df_dict <- function() {
df <- data.frame(german = c("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"),
english = c("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"),
stringsAsFactors = F)
return(df)
}
df <- df_dict()
df_g2e <- function(wd) {
df$english[which(df$german == wd)]
}
The microbenchmark:
print(summary(microbenchmark::microbenchmark(
g2e("So"),
df_g2e("So"),
times = 1000L, unit = "us")))
}
And the result:
expr min lq mean median uq max neval
g2e("So") 1.520 2.280 2.434178 2.281 2.661 17.106 1000
df_g2e("So") 12.545 15.205 16.368450 15.966 16.726 55.500 1000