The command for assigning a value to a variable is <-. You can basically
use any name for a variable, although it will cause problems if you give
a variable the same name as a function, so be careful not to
use c
or length
as a variable name. Although innocuous,
these are both functions in S-PLUS. If you do accidentally give a variable the
same name as a function, remove the variable from your .Data area (see below).
Variable names can be as long as you need, but should not contain blank
spaces. If you have two words in a variable name, such as ``Water Depth'',
you could write it as WaterDepth
, waterdepth
, or
water.depth
. You may not separate words with an underscore (that is
a special character in S-PLUS) or a dash (that would be interpreted as a
minus sign).
To assign the value 9
to the variable x
, type:
> x <- 9(Read this as ``x gets 9''.) Note that S-PLUS does not return any output after an assignment. If you type the variable name, S-PLUS will return its value (if you are ever unsure, this is a good way to confirm that an assignment was successful).
Now that x
has a value, it can be manipulated like any other number.
> sqrt(x) [1] 3 > y <- (5 * (x + 2)) - 3These manipulations do not affect the value of
x
, it is still 9
.
To change it, you must assign a new value to x
.
> sqrt(x) [1] 3 > x [1] 9 > x <- sqrt(x) > x [1] 3Text values can also be assigned to a variable:
> y <- "hello" > y [1] "hello"The variables
x
and y
are now stored in your .Data directory.
This means you will be able to use them for the remainder of this session
and any time you run S-PLUS in the future. For a list of objects in your
directory, use the objects()
command. Unneeded objects
may be removed with the remove
or rm
commands.
The two work the same, only remove
requires quotation marks
around the argument, for instance remove("x")
is the same
as rm(x)
.
Question: How do you exchange the values of x and y?