R Data Structures
# create vectors of data for three medical patients
President_name <- c("Omar Jeanmary", "Rose Lee", " Alicia Malcolm")
salary <- c( 30000.00, 40000.00, 5000.00)
Application_status <- c(FALSE, FALSE, TRUE)
# access the second element in body temperature vector
salary[2]
## [1] 40000
# include items in the range 2 to 3
salary[2:3]
## [1] 40000 5000
# exclude item 2 using the minus sign
salary[-2]
## [1] 30000 5000
# add ordered factor
Government <- factor(c("SEVERE", "MILD", "MODERATE"),
levels = c("MILD", "MODERATE", "SEVERE"),
ordered = TRUE)
Government
## [1] SEVERE MILD MODERATE
## Levels: MILD < MODERATE < SEVERE
# check for symptoms greater than moderate
Government > "MODERATE"
## [1] TRUE FALSE FALSE
President_name[1]
## [1] "Omar Jeanmary"
salary[1]
## [1] 30000
Application_status[1]
## [1] FALSE
Government[1]
## [1] SEVERE
## Levels: MILD < MODERATE < SEVERE
# create list for a president
subject1 <- list(fullname = President_name[1],
salary= salary[1],
Application_status = Application_status[1],
Government = Government[1])
subject1
## $fullname
## [1] "Omar Jeanmary"
##
## $salary
## [1] 30000
##
## $Application_status
## [1] FALSE
##
## $Government
## [1] SEVERE
## Levels: MILD < MODERATE < SEVERE
pt_data <- data.frame(President_name, salary, Application_status, Government = FALSE)
pt_data
## President_name salary Application_status Government
## 1 Omar Jeanmary 30000 FALSE FALSE
## 2 Rose Lee 40000 FALSE FALSE
## 3 Alicia Malcolm 5000 TRUE FALSE
# get a single column
pt_data$President_name
## [1] "Omar Jeanmary" "Rose Lee" " Alicia Malcolm"
# get several columns by specifying a vector of names
pt_data[c("salary", "Application_status")]
## salary Application_status
## 1 30000 FALSE
## 2 40000 FALSE
## 3 5000 TRUE
# accessing by row and column
pt_data[2, 2]
## [1] 40000
# accessing several rows and several columns using vectors
pt_data[c(1, 2), c(2, 3)]
## salary Application_status
## 1 30000 FALSE
## 2 40000 FALSE
# create a 2x2 matrix
m1 <- matrix(c(1, 2, 3, 4), nrow = 2)
m1
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
# equivalent to the above
m1 <- matrix(c(1, 2, 3, 4), ncol = 2)
m1
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
# create a 2x3 matrix
m2 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
m2
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
m4<-matrix(c(3,3,7,9,11,10),ncol = 2)
m4
## [,1] [,2]
## [1,] 3 9
## [2,] 3 11
## [3,] 7 10
#let us extract the first row
m4[1,]
## [1] 3 9
m4[,2]
## [1] 9 11 10