A basic concept in (statistical) programming is called a varibale.
A variable allows you to store a value (e.g.4) or an object (e.g. a function description) in R. You can then later use this variable’s name to easily access the value or the object that is stored within this variable.
You can assign a value 4 to a variable my_variable with the command: my_variable = 4.
Exercises1
1 2 3 4 5
> # Assign the value 42 to x > x = 42 > # Print out the value of the variable x > x [1] 42
Variable assignment(2)
Suppose you have a fruit basket with five apples. As a data ananlyst in training, you want to store the number of apples in a variable with the name my_apples.
Exercises2
1 2 3 4 5
> # Assign the value 5 to the variable called my_apples > my_apples <- 5 > # Print out the value of the variable my_apples > my_apples [1] 5
Variable assignment(3)
Every tasty fruit basket needs oranges, so you decide to add six oranges. As a data ananlyst, your reflex is to immediately create the variable my_orange and assign the value 6 to it. Next, you want to calculate how many pieces of fruit you have in total. Since you have given meaningful names to these values, you can now code this in a clear way:my_apples + my_oranges.
Exercise3
1 2 3 4 5 6 7 8
> # Assign a value to the variables called my_apples and my_oranges > my_apples = 5 > my_oranges = 6 > # Add these two variables together and print the result > print(my_apples + my_oranges) [1] 11 > # Create the variable my_fruit > my_fruit = my_apples + my_oranges
Apples and oranges
Common knowledge tells you not to add apples and oranges. But hey, that is what you just did, no:-)? The my_apples and my_oranges variables both contained a number in the previous exercise. The + operator works with numeric variables in R. If you really tried to add “apples” and “oranges”, and assigned a text value to the variable my_oranges (see the editor), you would be trying to assign the addition of a numeric a character variable to the variable my_fruit. This is not possible.
Exercise4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
> # Assign a value to the variable called my_apples > my_apples = 5 > # Print out the value of my_apples > my_apples [1] 5 > > # Add a character > my_oranges = 6 > my_oranges [1] 6 > > # New variable that contains total amount of fruit > my_fruit = my_apples + my_oranges > my_fruit [1] 11