Program R
Please write about the difference between the assignment operators <- and <<- ? You need to refer to help(assignOps) for this answer.
There are three different assignment operators: two of them have leftwards and rightwards forms.
The operators <-
assign into the environment in
which they are evaluated. The operator <-
can be
used anywhere.
The operators <-
can be used, almost
interchangeably, to assign to variable in the same environment.
The operators <<-
is normally only used in
functions, and cause a search to be made through parent
environments for an existing definition of the variable being
assigned. If such a variable is found (and its binding is not
locked) then its value is redefined, otherwise assignment takes
place in the global environment. Note that their semantics differ
from that in the S language, but are useful in conjunction with the
scoping rules of R. See ‘The R Language
Definition’ manual for further details and examples.
The <<-
operator is used for assigning to
variables in the parent environments (more like global
assignments). The rightward assignments, although available are
rarely used.
First, let’s look at an example.
x <- rnorm(100)
y <- 2*x + rnorm(100)
lm(formula=y~x)
The above code uses both <-
and =
symbols, but the work they do are different. <-
in
the first two lines are used as assignment
operator while =
in the third line does not
serves as assignment operator but an operator that specifies a
named parameter formula
for lm
function.
In other words, <-
evaluates the the expression
on its right side (rnorm(100)
) and assign the
evaluated value to the symbol (variable) on the left side
(x
) in the current environment. =
evaluates the expression on its right side (y~x
) and
set the evaluated value to the parameter of the name specified on
the left side (formula
) for a certain function.
We know that <-
and =
are perfectly
equivalent when they are used as assignment operators.
Get Answers For Free
Most questions answered within 1 hours.