introtor.lecture2.vectors

Welcome to R.


Variable

Name rules:

  • no space
  • not start with a number
  • split with period(usually) or make every first letter in each word, except the first one, capital(Camel Notation) e.g. my.variable myVariable

Make sure that the name of your variable is highly readable and understandable.

Assignment

  • use <- (its="" shortcut="" in="" rstudio="" is="" alt="" -)="" e.g.="" x-="">5
  • You can use ‘=’ for assignment, but we seldom write code is this way. While there’s an exception: when we assign values to parameters of a function, we use ‘=’ instead of <-.

Environments

On the top right of the RStudio. The environment is where R stores the variables and their values.
To clean the environment:

1
rm(list = ls())

In RStudio, all the notebooks open at the same time will ‘share’ the environment window.

Vectors

Create Vectors

numeric(10): default value is 0.
logical(5): default value is FALSE.
c(…) : list all the values and it can combine vectors together.

1
c(TRUE, FALSE, TRUE, TRUE, 1, TRUE)

The output is 1 0 1 1 1 1.

1
c(1, 2, 3, 4, "hey", 5)

The output is “1” “2” “3” “4” “hey” “5”

The colon operator

The colon operator takes two numbers and produces a vector of numbers starting at the first value and ending at the second number in increments or decrements of 1.
The numbers does not have to be an interger.

1
1.2:5.5

The output is 1.2 2.2 3.2 4.2 5.2

1
c(2:1, 0:6)

The output is 2 1 0 1 2 3 4 5 6

Random numbers

Thus, to generate 25 random values from a normal distribution with mean 100 and standard deviation 10, we have:

1
2
rnorm(25, 100, 10)
rnorm(25, mean = 100, 10)

Vectorized Operation

Vectorized operations are component-wise.
That means we applying the operation to corresponding elements in the same place.

1
(1:5) + (2:6)

The output is 3 5 7 9 11
The vectors can have different length and the operations are executed circularly, but it is quite strange to do so and there will be an warning in RStudio.
Also

1
(1:5) * 4 + 3

The output is 7 11 15 19 23

Use sum() function to calculate the sum of all the element of vectors.

Data Visualization: The Stripchart

1
2
3
4
5
6
7
8
9
stripchart( stripchart.vector, 
main = "Stripchart of random normal data",
xlim = c(60, 140), # This is the limit of x axis: c(leftPoint, rightPoint)
ylim = c(0, 2), # This is the limit of y axis: c(lowPoint, highPoint)
method = "jitter", # jitter means shaking
jitter = 0.4, # It will add random y-values to the elements
pch = 19, # Point character
cex = 1.2, # Size of the dots
col = "salmon2")

Tips:
To be more professional, the charts should not be so colorful.