── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.5.1 ✔ tibble 3.2.1
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.0.4
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
Access data items
One of the most basic needs of a programmer is to be able to access specific columns, rows, or data items in a data frame. We look at how to accomplish those on this page.
For the purposes of our work, we’re going to create this tiny data frame.
grades = data.frame(
instructor_id = c(1, 2, 3, 4, 5, 6, 7, 8, 9) * 2,
instr_first = c("Alice", "Bob", "Charlie", "David",
"Eve", "Stanislav", "Yolanda",
"Zoe", "Xavier"),
instr_last = c("Smith", "Jones", "Kline", "White",
"Zettle", "Bernard-Zza", "Zhang",
"Xu", "Zimmerman"),
subject = c("Math", "Math", "Math", "English",
"English", "English", "History",
"History", "History"),
grade = c("A", "B", "A", "C", "B", "A", "A",
"B", "A")
)
1 Whole data frame
We can access the whole data frame by simply typing its name:
2 Specific column
We can access a whole column at once either by name or by number. Let’s take a look.
2.1 By column name
We have several different ways of accessing a specific column by name. In all cases, one must know the name of the data frame and the name of the column. (Not surprising.)
[1] "Math" "Math" "Math" "English" "English" "English" "History"
[8] "History" "History"
[1] "Math" "Math" "Math" "English" "English" "English" "History"
[8] "History" "History"
[1] "Math" "Math" "Math" "English" "English" "English" "History"
[8] "History" "History"
2.2 By column number
We can also access a specific column by column number:
[1] "Math" "Math" "Math" "English" "English" "English" "History"
[8] "History" "History"
This form returns a vector
of values, as you can see.
We can use an alternate form that returns a list, also using a column number:
And, yes, it is a list:
3 Parts of a specific column
Both of the following return the first through fourth values of the subject
column.
4 Parts of a specific row
This returns the third through fifth values of row 7.
5 A specific item in a specific column
R has multiple ways — that’s no surprise by now, eh? — of accessing specific items in a specific column. Each of these access the item in row 7 of the subject
column: