Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R assignment operators

Tags:

r

I was checking R assignment operators and trying to understand how they work, so I wrote the following code:

> somevar1 <- "stuff1"
> "stuff2" -> somevar2
> somevar3 = "stuff3"
> "stuff4" <- somevar4
Error: object 'somevar4' not found
> "stuff5" = somevar5
Error: object 'somevar5' not found
> `<-`(somevar6, "stuff6")
> `=`(somevar7, "stuff7")
> `=`("stuff8", somevar8)
Error: object 'somevar8' not found
> `->`("stuff9", somevar9)
Error in `->`("stuff9", somevar9) : could not find function "->"
> `<<-`(somevar10, "stuff10")
> `->>`("stuff11", somevar11)
Error in `->>`("stuff11", somevar11) : could not find function "->>"

Up to the line, where somevar9 is being used, everything seems in line with expectations. However, I don't get why I'm getting the errors like Error in ->("stuff9", somevar9) : could not find function "->" and Error in ->>("stuff11", somevar11) : could not find function "->>". Should they not exist for the -> and ->> operators to work? Thanks in advance!

like image 863
abudis Avatar asked Feb 14 '26 04:02

abudis


1 Answers

When the R parser comes across a -> b it calls '<-'("b", a) and when it comes across a ->> b it calls '<<-'("b", a)

We can see this explicitly if we do the following:

as.call(quote(a <- 1))
#> a <- 1
as.call(quote(a <<- 1))
#> a <<- 1
as.call(quote(1 -> a))
#> a <- 1
as.call(quote(1 ->> a))
#> a <<- 1

Created on 2022-01-27 by the reprex package (v2.0.1)

like image 112
Allan Cameron Avatar answered Feb 16 '26 18:02

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!