Creating Variables in R
You can use R like a basic calculator by simply typing numbers separated by the plus symbol.
5 + 2
output: 7
That is useful, but what if the values 5 and 2 could change, or you just want a better idea of what they represent? The solution is to represent these numbers as variables. To create a variable we put the variable name we want on the left, add a left-pointing arrow (“<“ followed by “-”), and then specify the number(s) we want to assign. In R, we can replace the left-facing arrow with an “=” sign interchangeably.
Hotdogs <- 5
Milk <- 2
Hotdogs + Milk
output: 7
With the new variables, we have an idea of what 5 and 2 represent, the cost of hotdogs and milk respectively. We can also have a variable represent a string of numbers, or what we call a vector in R. To create a vector with more than one number we can use c(), where each number is separated by a comma.
Prices <- c(5, 2)
print(Prices)
output: 5 2
This is convenient because we can now use handy functions on the Price variable to understand more about the data. For example the sum and mean of the prices.
sum(Prices)
output: 7
mean(Prices)
output: 3.5
In the next blog, we will go over useful functions to create some commonly used vectors without using c().