Data Frames
- Make a data frame with 3 columns and 5 rows in which:
- The first column contains the sequence of numbers from 1 to 5
- The second column contains a character vector
- The third column contains a logical vector
df=cbind.data.frame(N=1:5, A=c("a", "b", "c", "d", "e"),C=c(TRUE, FALSE, TRUE, FALSE, TRUE) )
df
## N A C
## 1 1 a TRUE
## 2 2 b FALSE
## 3 3 c TRUE
## 4 4 d FALSE
## 5 5 e TRUE
- Extract the first two columns and first two rows. HINT: Use the same
notation as matrices.
df[1:2, 1:2]
## N A
## 1 1 a
## 2 2 b
- Extract the second column using the column names. You can use
[ ]
or $
; use both the method in two different
answers.
df[,"A"]
## [1] "a" "b" "c" "d" "e"
df$A
## [1] "a" "b" "c" "d" "e"
- Extract rows where the 1st column is larger than 3. HINT: You can
get a logical vector using the
>
operator, and logical
vectors can be used in [ ]
when subsetting.
df[df$N>3,]
## N A C
## 4 4 d FALSE
## 5 5 e TRUE
- Convert the data frame to the matrix format. HINT: Use
as.matrix()
. Observe what happens to numeric and logical
values in the data frame.
as.matrix(df)
## N A C
## [1,] "1" "a" "TRUE"
## [2,] "2" "b" "FALSE"
## [3,] "3" "c" "TRUE"
## [4,] "4" "d" "FALSE"
## [5,] "5" "e" "TRUE"
Lists
- Make a list using the
list()
function. Your list should
have 4 elements:
- two vectors (a logical one and a numeric one)
- a matrix
- a data frame.
el1=1:100
el2=c(rep(FALSE, 10), rep(TRUE, 20))
m=matrix(1:25, byrow = T, ncol=5)
l=cbind.data.frame(name=c("Gio", "Rob", "Anne"), age=c(12, 15, 17))
lista=list(el1, el2, m, l)
lista
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## [91] 91 92 93 94 95 96 97 98 99 100
##
## [[2]]
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
## [13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [25] TRUE TRUE TRUE TRUE TRUE TRUE
##
## [[3]]
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5
## [2,] 6 7 8 9 10
## [3,] 11 12 13 14 15
## [4,] 16 17 18 19 20
## [5,] 21 22 23 24 25
##
## [[4]]
## name age
## 1 Gio 12
## 2 Rob 15
## 3 Anne 17
- Extract the first column of the matrix contained in the list.
lista[[3]][,1]
## [1] 1 6 11 16 21