R : how to name String without creating an object
This question already has an answer here:
It is because <-
and =
are not the same. For (just about) every purpose except when used inside a function call , <-
and =
are the same. If you want to pass a named argument, you have to use =
not <-
. myFunction(X <- expression)
will evaluate expression
and save the result into the (global) variable X
, and put the result as the first ( unnamed ) argument to myFunction
. Contrast to myFunction(X = expression)
which pass the expression as the named X
argument to myFunction
and will not create a (global) variable X
.
My explanation is a little garbled - I highly recommend reading ?'<-'
(the helpfile for <-
and =
) which is clearer.
In the first one:
args <- list(place <- "Agra", adjective <- "huge")
R evaluates place <- "Agra"
in the global environment, which returns "Agra"
. It also evaluates adjective <- "huge"
in the global environment similarly, returning "huge". Then it places the results ("Agra" and "huge") into the list()
call as unnamed arguments, so essentially what you are doing is
place <- "Agra"
adjective <- "huge"
args <- list("Agra", "huge")
That is why you get global variables, and the args
list has no names. If this is what you want, you should use the long form not the short form to write it. Using the first form could lead to unexpected or confusing side-effects.
In the second option
args <- list(place = "Agra", adjective = "huge")
it is simply passing the named argument "place" with value "Agra", and the named argument "adjective" with value "huge". Since list()
uses argument names as list names, that's why you get a named list. Also, this will not create global variables place
and adjective
.
上一篇: 为什么数据框的列名使用=和<不同