3.5 Subsetting / manipulating tibbles
- Extract column by name:
# with the $
$letters mytibble
## [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 [[]]
"letters"]] mytibble[[
## [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)
"letters"] mytibble[
## # 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
1] mytibble[,
## # 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
1]] mytibble[[
## [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
iris
a tibble? How can you tell? Try to runis_tibble
. - Convert
iris
to a tibble. Save in a new objecttbl_iris
. Runis_tibble
ontbl_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.
<- tibble(iris)
tbl_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:
"Species"]
tbl_iris[# create a vector:
"Species"]] # same as tbl_iris$Species tbl_iris[[