14) Creating a Numeric Variable by Assignment

This Blog entry is from the Getting Started in R section in Learn R.

Start by creating a new script:

creating-a-new-script-in-rstudio.png

A blank script window will be created that will be the target:

a-new-script-in-r-studio.png

Variables in R are created by assignment,  the process of setting a value.  The operator or command for assignment is the character combination of "<-".  To create and assign a numeric variable start by typing into the script window:

Numeric <- 1
creating-a-numeric-variable-by-assign-in-r-rstudio.png

Run the script to console:

r-console-numeric-variable-created-by-assign.png

A variable with the name Numeric has now been created.   It can be seen that RStudio has also recognised the creation of a new variable in the Environment Values pane towards the top right hand side of RStudio:

the-variable-environment-window-in-rstudio.png

script to console.  In this example,  create a new line in the script and type the name of the variable:

Numeric
write-numeric-variable-to-r-console.png

Run the line of script to console:

numeric-variable-written-out-to-r-console.png

It can be seen that the assigned value is written out.

The mode() function is intended to disclose the variable type, taking the variable name as the paramater.  Create a new line in the script editor and disclose the variable type, start by typing:

mode(Numeric)

Run the line of script to console:

using-the-mode-function-to-check-variable-type-in-r-console.png

It can be observed that the variable type has been returned as numeric.  It is also possible to assign a variable as the result of arithmetic or function output.  For example,  type into the script editor:

NumericResult <- 1 + 1
performing-some-basic-addition-on-numeric-variable-in-r-console.png

Run the line of script to the console:

numeric-variable-created-by-assign-and-addition-in-rstudio-variable-environment.png

It can be observed that the NumericVariable has been created and is available in the Environment Variables windows, and it would also return in the console when referencing the variable directly:

outputting-a-variable-to-r-console.png