Create variables by assigning a value
Can you assign multiple values to a variable?
Sure you can! A variable can hold one value but it can also hold a row or even a table of values. In the latter case you need to create the variable by running a function (see next topic).
x <- 1:10
x
[1] 1 2 3 4 5 6 7 8 9 10
Programming tip: use variables
x <- 1:10
x
[1] 1 2 3 4 5 6 7 8 9 10
x + 10
[1] 11 12 13 14 15 16 17 18 19 20
1:10 + 10
[1] 11 12 13 14 15 16 17 18 19 20
It’s useful to create variables: in all code that follows you can use the name of the variable (x) instead of always having to type the full code (1:10).
Of course the second command (1:10 + 10), where you don’t use the variable x also works, you are not obliged to create a variable to store the values in.
That being said, when you start programming it’s often easier to use multiple small steps instead of one elaborate command. So it’s a good idea to create many variables that make the commands simpler to understand.
No spaces in (variable) names!
Variable names cannot contain spaces. Every name you create in R whether it’s a name for a variable or for a row or a column in a table or for an object in a list, must be free of spaces.