Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a constant inside R package?

How to create the constant variable inside the R package, the value of which cannot be changed? In other words, how can we lock the pair name-value in package environment?

Example: In my package I am using a quantile of Normal distribution in loops of different functions, and do not want to calculate (or create) it all the time.

I tried k_q3 <- qnorm(1 - 0.01/2); lockBinding("k_q3", environment()), but it does not work.

UPDATE: The method above actually is workable. One cannot change the k_q3 neither inside package, not outside.

like image 814
irudnyts Avatar asked Oct 07 '15 14:10

irudnyts


People also ask

How do you create a constant variable?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

What is a constant script?

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.


1 Answers

The simplest and cleanest way would be to create a function, e.g.

K_Q3 <- function() { qnorm(1 - 0.01/2) }

Note that calling functions in R has a non-negligible overhead. You should avoid calling it in loops, or copy it to a local variable before.

like image 101
Karl Forner Avatar answered Oct 19 '22 10:10

Karl Forner