3.18 Variables

20200501 We can store values, such as the resulting value from invoking a function (Section 3.5), into a variable. A variable is a name that we can use to refer to some location in the computer’s memory. Into this location we store the data while our programs are running so that we can refer to that data by the specific variable name later on. We use the assignment operator base::<- to do so:

# Add two numbers and assign the result into a variable.

v <- sum(1, 2)

We can access the value stored in the variable (or actually stored in the computer’s memory that the variable name refers to) simply by requesting through the R Console that R `run'' the commandv. We do so below with a line containing justv. In fact the R software actually runs the [base::print()](https://www.rdocumentation.org/packages/base/topics/print){ target="_blank" } function to display the contents of the computer's memory thatv` refers to—this is a convenience that the R software provides for us.

# Print the value stored in a variable.

## [1] 3
## [1] 3

By indexing the variable with [1] we can ask for the first item referred to by v. Noting that the variable v is a vector with only a single item when we try to index a second item we get an NA (meaning not available or a missing value).

# Access a particular value from a vector of data.

## [1] 3
## [1] NA

Your donation will support ongoing development and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.