Values, Variables, Functions
Before we do anything in R, let’s first establish three terms that will pop up again and again: Values, Variables and Functions.
A value is the actual data, like the amount of bats in an area, the forest type or a measurement of soil pH. In R, a value belongs to a data type that depends on what the value should represent:
numericrepresents numberscharacterrepresents textlogicalrepresents whether something is TRUE or FALSE
# numeric
1
68542
4.5
# character
"f"
"Hi Mom!"
# logical
TRUE
FALSEA variable in R is a name that represents out data. Think of it as a container in which you can store a value. You can assign values to variables either with <- or =. The name of the variable in on the left, the assigned value on the right. How you name the variable is up to you. However I recommend you use recognizable names! Don’t be lazy - Longer, descriptive names help immensely when you read your code again later and you want to know what a certain variable actually contains.
23 # just the value
number <- 23 # store the value in a variableStored values in variables are not persistent. You can modify them or even overwrite them - even with values of a different type. So be careful when choosing the names of variables that you have not already used them in the script.
number = "odonata"Functions are methods that do something with values or values that are stored in variables. Think of them as a machine, where you put in you value and get some result out.
number = 23
cos(number)[1] -0.532833
Functions are identified by their specific keyword, e.g. the method that calculates the cosine of a certain number is called cos. The function name is followed by parenthesis () making it cos(). In the parenthesis, you define the so called arguments of the function. This can be the input value, options or parameters to specify what the function should. Which arguments a functions requires is written on the help page of the function. You can access the help page with ?cos() or by searching for the function in the ‘Help’ tab in Rstudio (bottom right panel).
# the cos function needs the argument x of type numeric
cos(x = 0)[1] 1
# it throws an error otherwise
cos(x = "3.14")Error in cos(x = "3.14"): non-numeric argument to mathematical function
# argument names can be neglected
cos(1)[1] 0.5403023
Putting everything together
result <- cos(23)With values, variables and function, you now know the basic building block of R code. So a line like this you can verbalize as “Put the value 23 in the cosine function and store the result in a variable that is called result”. Here is a visual representation of this line of code: