In the previous two steps we encountered variables and constants of different types.
Let's take a closer look ...
In R one creates variables by giving them a name and assigning a value, as we did with
the_answer = 6*7
The name can consist of letters, numbers and the two characters _ and .
but do not use _ or . or a number as the first character.
Examples of valid names:
var1
the_strength_of_Luisa
dog.leg
There are reserved words, which cannot be used to name variables, you can get a list with
the help procedure:
help(reserved)
You probably don't want this line in your R script, so I suggest you type help(reserved) in window 2 bottom left
and hit Enter. Indeed window 2 is a fully functional R terminal and I use it to try out things and keep whatever
code I want saved in window 1, i.e. in my R script.
Whenever we create a variable, R figures out the data type from the assigned value and/or operation(s).
We already encountered several different data types:
logical: TRUE or FALSE , abbreviated as T or F (e.g. the parameter header=T in the read.csv procedure)
numeric: the_answer = 6*7 was our first example, 3.1415 would be another
integer: R does not distinguish 6 from 6.0 , but if one wants to explicitly use a whole number
it needs do be indicated with the letter L, e.g. 6L
the_answer = 6L*7L
is now an integer and not a numeric variable.
strings: We have used the string "blue" in the plot procedure and one can display strings e.g. with the print procedure
print("blue")
R uses vectors as basic building blocks, collections of elements with the same data type.
ryder$Close was an example of a vector.
But the_answer was a vector too, just a small vector with 1 element only.
We access the elements of a vector with the [] operator, so that
ryder$Close[3]
would be the 3rd element of the vector, i.e. the 3rd entry of the data column.
And the_answer[1] would be the one and only element of the vector the_answer.
Notice that vector indices begin with 1 and not 0 as in some other programming languages.
One can generate a vector e.g. with the function c(), used so often that it has a really short name:
vec1 = c(1.1, 2.7, 3.2, 4.6)
creates a numeric vector with 4 elements.
vec2 = c("me","my","friend","and","you")
creates a vector with 5 strings as elements.
Last but not least, the : operator can be used to create a specific vector of integers
vec3 = 2:7
creates a vector with 5 integers as elements, the whole numbers 2, 3, 4, 5, 6, 7.
exercise: Create vectors of different sizes and types - watch in window 3 what it displays for each one.
No comments:
Post a Comment