To create an object and assign it a numerical value, do this:
x <- 5
You don’t have to assign value. You can create a NULL object for later use:
y <- NULL
As a general matter, one could force a command to print out its results to the screen by enclosing it in parentheses. When you execute the command x <- 25, R creates the object x, assigns it the value of 25, and then silently prompts you for the next command. But the command (x <- 25) does everything that x <- 25 does and in addition gives you on-screen output. Try the following:
(z <- 100)
## [1] 100
The value assigned to an object does not have to be of the numerical type, as in x <- 5. The assigned values could be of the character type – e.g., x <- "Donald Trump" – or of the logical type – e.g., x <- TRUE.
You can check whether the object x exists:
exists("x")
## [1] TRUE
You’ll get TRUE if x exists, and FALSE otherwise.
Here, exists() is an example of a function. You feed a function an object and it does something – presumably something useful – with the object.
That’s not to say that you necessarily have to feed a function an object for it to do something useful. For example, you can find the names of all currently defined objects:
ls()
## [1] "x" "y" "z"
If there are no currently defined objects, this returns character(0).
Information about object x can be obtained from the following functions:
summary(x)
str(x)
class(x)
To remove an object x use this function: rm(x).
Value can be assigned to an object directly, as in the examples above, or indirectly. The command exists(x) that we saw above returns data of the logical type, either TRUE or FALSE. So, we can do this indirect assignment: y <- exists(x).
You don’t need to pre-define an object before you feed it to a function. Consider this code chunk:
x <- 25
sqrt(x)
## [1] 5
The sqrt() function gives you the positive square root of a positive number. In this case, it returns 5 as the positive square root of 25. But we could have simply written sqrt(25) and gotten the same answer.
Similarly, abs(x) and abs(25) return the absolute value of x and the number 25, respectively.
The commands log(x, base = 10) and log(25, base = 10) return the base-ten logarithm of x and the number 25, respectively.
There are numerous such functions. Just you wait!