- Intro to basics
> # An addition
> 5 + 5
[1] 10
> # Assign the value 42 to x
> x <- 42
>
> # Print out the value of the variable x
> x
[1] 42
> # Declare variables of different types
> my_numeric <- 42
>
> # Check class of my_numeric
> class(my_numeric)
[1] "numeric"
-Vectors
# create a vector with the combine function c()
> numeric_vector <- c(1, 10, 49)
>
> numeric_vector
[1] 1 10 49
> # Roulette winnings from Monday to Friday
> roulette_vector <- c(-24, -50, 100, -350, 10)
>
> poker_vector
[1] 140 -50 20 -120 240
>
> # Assign days as names of poker_vector
> names(poker_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
>
> poker_vector
Monday Tuesday Wednesday Thursday Friday
140 -50 20 -120 240
> A_vector <- c(1, 2, 3)
> B_vector <- c(4, 5, 6)
>
> # Take the sum of A_vector and B_vector
> total_vector <- A_vector + B_vector
>
> # Print out total_vector
> total_vector
[1] 5 7 9
>
> # Total of A_vector
> total <- sum(A_vector)
> total
[1] 6
>
> # Define a new variable based on a selection
> selection_vector <- B_vector[c(1:2)]
> selection_vector
[1] 4 5
>
> # Calculate the average
> mean(A_vector)
[1] 2
-Matrics
> # Construct a matrix with 3 rows that contain the numbers 1 up to 9
> matrix(1:9, byrow=TRUE, nrow=3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> # Box office Star Wars (in millions!)
> new_hope <- c(460.998, 314.4)
> empire_strikes <- c(290.475, 247.900)
> return_jedi <- c(309.306, 165.8)
>
> # Create box_office
> box_office <- c( new_hope, empire_strikes, return_jedi )
>
> # Construct star_wars_matrix
> star_wars_matrix <- matrix( box_office, byrow=TRUE, nrow =3)
> # Box office Star Wars (in millions!)
> new_hope <- c(460.998, 314.4)
> empire_strikes <- c(290.475, 247.900)
> return_jedi <- c(309.306, 165.8)
>
> # Create box_office
> box_office <- c( new_hope, empire_strikes, return_jedi )
>
> # Construct star_wars_matrix
> star_wars_matrix <- matrix( box_office, byrow=TRUE, nrow =3)
> star_wars_matrix
[,1] [,2]
[1,] 460.998 314.4
[2,] 290.475 247.9
[3,] 309.306 165.8
> # Box office Star Wars (in millions!)
> new_hope <- c(460.998, 314.4)
> empire_strikes <- c(290.475, 247.900)
> return_jedi <- c(309.306, 165.8)
>
> # Construct matrix
> star_wars_matrix <- matrix(c(new_hope, empire_strikes, return_jedi), nrow = 3, byrow = TRUE)
> star_wars_matrix
[,1] [,2]
[1,] 460.998 314.4
[2,] 290.475 247.9
[3,] 309.306 165.8
>
> # Vectors region and titles, used for naming
> region <- c("US", "non-US")
> titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")
>
> # Name the columns with region
> colnames(star_wars_matrix) <- region
> star_wars_matrix
US non-US
[1,] 460.998 314.4
[2,] 290.475 247.9
[3,] 309.306 165.8
>
> # Name the rows with titles
> rownames(star_wars_matrix) <- titles
>
> # Print out star_wars_matrix
> star_wars_matrix
US non-US
A New Hope 460.998 314.4
The Empire Strikes Back 290.475 247.9
Return of the Jedi 309.306 165.8