Objects and Data Structures
Objects and Data Structures
Objects and Assigning Values
What makes R a more flexible programming language than, say, Stata, is that it allows us to call objects by ‘name.’ What the heck does that mean? It means that as an object-oriented programming language, R allows us to store objects on the workspace and give them a name. Then, instead of retyping or re-entering whatever data we have stored, we can simply refer to the object we have created and named. We do this using an assignment arrow which is a ‘less than’ symbol followed by a dash, with the name of the object on the left side and whatever is being assigned to it on the right hand side. For example, X <- 2, produces an object ‘X’ (note that R is case sensitive) and assigns to it the numeric value of two. Below, X is a type object called a ‘scalar,’ and its class (as indicated using the class command) is numeric.
X <- 2 X > [1] 2 sqrt(X) > [1] 1.414214 X^2 >[1] 4 x # here I typed a lower case x, which returns the error below. > ## Error in eval(expr, envir, enclos): object 'x' not found class(X) > [1] "numeric"
This might not seem that important to you now, but having the ability to name objects and call them by name is essential when one wants to write a program to solve a particular problem. Given that the size of R’s workspace is only limited by the memory of the computer one is using, it is easier to name more objects if doing so makes your code clearer. The best code is that which is clear not only to the original programmer, but would also be clear to anyone who begins from the top of the script and executes the code line-by-line. Comments can help with clarity, as can clear object names.