Sunday 9 December 2018

The Assignment Operator in R: Does "




In R, I have come across an example in which both = and <- are valid for assignment. e.g.




> y = c("hello", "world")
> y
[1] "hello" "world"
> y2 <- c("hello", "world")
> y2
[1] "hello" "world"


I have also come across an example in which = is invalid and <- is valid. e.g.




> quote(y[1] <- 1)
y[1] <- 1
> quote(x[1] = 1)
Error: unexpected '=' in "quote(x[1] ="


My question is, are there any cases in which the vice versa is true? i.e. <- is invalid whilst = is valid?



Reason for asking this question is to understand whether to stick with =, <-, or either (depending on circumstances) when performing assignment operation in R.




This will really help me setting up my mindset when performing coding in R.



Thank you!


Answer



R has several assignment operators. Per the documentation




The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.





The only place I am aware of where you must use the <- operator is naming items of a list in attach.



This does not work:



> attach(what <- list(foo <- function(x) print(x)))


but this does:




> attach(what <- list(foo = function(x) print(x)))


I don't actually know why this is. If anyone else knows I'd love to learn why.



I am also compelled to discourage use of any of the blasphemous right assignment operators.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...