Go back to Index

  1. Take a look to diag function. Create a 21-by-21 matrix called “m” with the sequence 10 to 0 to 10 (i.e. 10, 10,…,0,1,..,10) in the diagonal. The rest of the elements should be zero.
a_matrix <- diag(c(seq(10,0), seq(1,10)))

a_matrix <- diag(abs(seq(-10,10)))
x <- c(seq(10,0),seq(1,010))
m <- diag(x)
  1. What is the length of the following list:
length(list(a =2, list(b=2, g=3, d=4), e=NULL))
## Answer: 3
  1. Create the following matrix:

m1 <- matrix(c(1,2,3,4), ncol=2)

Using [] retrieve the element in the first row and first column, then the element in the second row and second column. Finally, retreive the entire second column.

m1 <- matrix(c(1,2,3,4), ncol=2)

m1[1,1]

m1[2,2]

m1[,2]
  1. Using the data frame E created above, include a new column: country = c(“US”, “Canada”, “US”, “Mexico”, “Japan”)
E <- data.frame(
            age = c(20,24,26,23,29),
            sex = c("Female","Male","Female","Male","Female"),
            treatment = c(1,0,0,1,1),
            income = c(1000,1500,2000,2500,3000)
            )

E$country <- c("US", "Canada", "US", "Mexico", "Japan")