Variable Assignment
- The variables can be assigned values using leftward, rightward and equal to operator. …
- Note − The vector c(TRUE,1) has a mix of logical and numeric class. …
- To know all the variables currently available in the workspace we use the ls() function.
Variable assignment in R is a bit different from other languages. Rather than using an = sign, we typically use a less-than sign, < ,followed by a minus, –. An equals sign, =, still works, but there are arguments about its readability in addition to instances where it can actually muck up your code. I suggest you stick with ← for assignment in R, if for no other reason than it’s expected (Google’s R style manual, which is widely used, prohibits = for assignment).
myVar <- 15 print(myVar
Notice the following is also valid:
myVar = 15 print(myVar)
You can also assign variables the other way around in R.
"helloWorld" -> myVar
The string “helloWorld” is now stored in the myVar variable. Note that this would produce an error if we got mixed up and tried to plug an undefined variable object into a string, as in:
myVar -> "helloWorld" Error: object 'myVar' not found
Scoping of variables is something to consider as well. <<- acts as the “superassignment” operator and is useful for closures. A good example on how to use this can be found on stackoverflow.
A variable in R can be defined using just letters or an underscore with letters, dots along with letters. We can even define variables as a mixture of digits, dot, underscore and letters.