Syntax
Much of the syntactic structure of R will seem familiar to you if you have experience in C, C++, Python Perl, or many other languages. Statements are separated from each other by newlines, although semicolons can also be used; like C, C++ and Perl, blocks of code—such as the code to be executed when an statement is satisfied, are enclosed in braces (and, for readability, should typically be indented), as will be demonstrated below.
You assign values to variables with or
, although the former is preferred (in Rstudio pressing the
and
(minus) key will insert the
for you). Case matters in variable names—
and
would be different variables. To learn the value of a variable, you simply type the variable name and the result will be all of the values for that variable. If you want a particular value, you would use an index in square brackets, again noting that in R, indexes start at one, not zero.
Vector Example:
The first command in the code block below creates a variable called a
and sets its value to the numeric vector [1, 3, 6, 9]. The <-
is an assignment operator in R. You can also use =
as an assignment operator as shown in the next example. The second command (on the second line) asks R to display the value of a
. The third line is output, where the value is displayed. One the fourth line, the command asks R to retrieve the third value from a
, and the fifth line shows the retrieved value as output.
Matrix Example:
Program Control is achieved with statements and
and
loops
if...else syntax:
Note that the signs are added by the interpreter or IDE, because the statement is not complete; you can break out of this multiline mode with the escape key
. In a script (rather than when typing into the console), it would be preferable in most cases to indent the contents of the code block.
loop syntax:
loop syntax:
You can access help for a function by typing (you should enclose the function name in quotation marks) or, more succinctly,
. To exit R, type
or
. You will be asked if you want to save your workspace image, which would mean that in your next session you will be able to access the command history and any user-defined objects created or assigned in this workspace. It is possible to clear everything in your workspace using this command:
Otherwise, you can remove individual items from your workspace by name, so that to remove items ,
and
, you would type