letters [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
Dataframes are tables, with rows and columns.
Imagine we have a couple of vectors (see the Store data with vectors flash card), and we want to put them together as two columns of a data frame.
For example, R has some built-in vectors that contain all the letters of the alphabet.
letters contains all the letters in lowercase:
letters [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
And LETTERS contains all the letters in uppercase.
LETTERS [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
Now, to make a dataframe, we can use the tidyverse function tibble().
Inside tibble(), we write the names that we want each column to have, then =, then the values that we want in those columns.
tibble(
lower = letters,
upper = LETTERS
)# A tibble: 26 x 2
lower upper
<chr> <chr>
1 a A
2 b B
3 c C
4 d D
5 e E
6 f F
7 g G
8 h H
9 i I
10 j J
# i 16 more rows
Careful: all vectors that you want to use as columns in the same tibble should have exactly the same length. In other words, they should contain the exact same number of items.
If they don’t, you’ll get an error that says “Tibble columns must have compatible sizes”. For example:
tibble(
lower = letters, # length 26
upper = LETTERS, # length 26
numbers = c(1, 2, 3, 4, 5) # length 5
)Error in `tibble()`:
! Tibble columns must have compatible sizes.
• Size 26: Existing data.
• Size 5: Column `numbers`.
ℹ Only values of size one are recycled.