my_vector <- 1:20
my_vector
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
dim(my_vector)
## NULL
length(my_vector)
## [1] 20
The dim() function allows you to get OR set | the dim attribute for an R object.
dim(my_vector) <- c(4,5)
dim(my_vector)
## [1] 4 5
attributes(my_vector)
## $dim
## [1] 4 5
my_vector
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 5 9 13 17
## [2,] 2 6 10 14 18
## [3,] 3 7 11 15 19
## [4,] 4 8 12 16 20
my_vector is now a matrix
class(my_vector)
## [1] "matrix" "array"
a matrix is simply an atomic vector with a | dimension attribute. A more direct method of creating the | same matrix uses the matrix() function.
my_matrix <- my_vector
?matrix
## starting httpd help server ... done
my_matrix2 <- matrix(data=1:20, nrow=4, ncol=5)
The identical() function will tell us | if its first two arguments are the same
identical(my_matrix, my_matrix2)
## [1] TRUE
Now, imagine that the numbers in our table represent some | measurements from a clinical experiment, where each row | represents one patient and each column represents one | variable for which measurements were taken. We may want to label the rows, so that we know which | numbers belong to each patient in the experiment. One way to do this is to add a column to the matrix, which contains| the names of all four people.
patients <- c("Bill", "Gina", "Kelly", "Sean")
patients
## [1] "Bill" "Gina" "Kelly" "Sean"
use the cbind() function to 'combine columns'.
cbind(patients, my_matrix)
## patients
## [1,] "Bill" "1" "5" "9" "13" "17"
## [2,] "Gina" "2" "6" "10" "14" "18"
## [3,] "Kelly" "3" "7" "11" "15" "19"
## [4,] "Sean" "4" "8" "12" "16" "20"
Combining the character vector with our matrix of numbers caused everything to be enclosed in double quotes. Matrices can only contain ONE class of data.
The data.frame() function allows us to store our character vector of names right alongside our matrix of numbers. The data.frame() function takes any number of arguments and returns a single object of class data.frame that is composed of the original objects.
my_data <- data.frame(patients, my_matrix)
my_data
class(my_data)
## [1] "data.frame"
Label Columns
cnames <- c( "patient", "age", "weight", "bp", "rating","test")
use the colnames() function to set the colnames | attribute for our data frame
colnames(my_data) <- cnames
my_data