R Data Frame Access
Data frame access pulls one column, one row or a set of matching rows from a table. The selected part can be printed, stored or changed.
Read columns by name
The dollar sign reads the name column as a vector. Double brackets with a name read the age column the same way.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(df$name)
print(df[["age"]])Read a row and a column
The first row prints as a small data frame. The age column then prints as a plain vector.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(df[1, ])
print(df[, "age"])Filter rows with brackets
The condition inside the brackets tests each age against 28. Only the rows for Ana and Cy stay.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(df[df$age > 28, ])Filter rows with subset
subset names the column directly inside its condition. It keeps the same two rows as the bracket form.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(subset(df, age > 28))Add a column
A new name after the dollar sign creates a score column. The printed table now shows all three columns.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
df$score <- c(88, 92, 79)
print(df)Example
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
df$score <- c(88, 92, 79)
print(subset(df, age > 28))Key points
- df$name reads the column called name.
- df[["age"]] reads the column called age.
- df[1, ] reads the first row as a small data frame.
- df[, "age"] reads a column by name inside brackets.
- A condition inside brackets keeps only the rows that match.
- subset() filters rows with a condition that names columns directly.
- df$score with an assignment adds a new column.
In this example, a score column joins the frame first. subset then keeps the two students older than 28 with their scores attached.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does df[df$age > 28, ] return?