3.5 Subsetting / manipulating tibbles
- Extract column by name:
# with the $
mytibble$letters##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V"
## [23] "W" "X" "Y" "Z"# or the [[]]
mytibble[["letters"]]##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V"
## [23] "W" "X" "Y" "Z"# Note: with simple square brackets, you extract a sub-tibble (it remains a 2 dimensional object)
mytibble["letters"]## # A tibble: 26 x 1
##    letters
##    <chr>  
##  1 A      
##  2 B      
##  3 C      
##  4 D      
##  5 E      
##  6 F      
##  7 G      
##  8 H      
##  9 I      
## 10 J      
## # … with 16 more rows- Extract column by position/index:
# sub-tibble with one column
mytibble[, 1]## # A tibble: 26 x 1
##    letters
##    <chr>  
##  1 A      
##  2 B      
##  3 C      
##  4 D      
##  5 E      
##  6 F      
##  7 G      
##  8 H      
##  9 I      
## 10 J      
## # … with 16 more rows# corresponding vector
mytibble[[1]]##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V"
## [23] "W" "X" "Y" "Z"HANDS-ON
We will work with the built-in dataset iris:
- Is irisa tibble? How can you tell? Try to runis_tibble.
- Convert iristo a tibble. Save in a new objecttbl_iris. Runis_tibbleontbl_iris.
- Show all rows of tbl_iris.
- Show the first 3 rows of tbl_iris.
- Extract column Species.
Answer
# Is iris a tibble?
is_tibble(iris)
# Convert iris to a tibble. Save in a new object tbl_iris.
tbl_iris <- tibble(iris)
# Show all rows from tbl_iris.
print(tbl_iris, n=Inf)
# Show the first 3 rows from tbl_iris.
print(tbl_iris, n=3)
# Extract column Species.
  # create a tibble with only one column:
tbl_iris["Species"] 
  # create a vector:
tbl_iris[["Species"]] # same as tbl_iris$Species