ZetCode

R data frames

last modified November 19, 2026

A data frame is R's table: rows are observations, columns are variables, and each column may have its own type. A data frame is implemented as a named list of vectors that all share the same length, so it combines the flexibility of a list with the rectangular shape of a matrix. Most data analysis in R starts with a data frame, and the functions that read files return one by default. This article shows how to build a data frame, inspect its structure, select columns and rows, add and remove variables, sort records, and combine two tables by rows, columns, or a shared key.

Creating a data frame

The function data.frame takes vectors as arguments and uses the argument names as column names. Every vector must have the same length, because the values at one position form one row. The next script builds a small table from three vectors and prints it.

building.R
name <- c("Ada", "Grace", "Alan")
score <- c(90, 85, 66)
passed <- c(TRUE, TRUE, FALSE)
students <- data.frame(name, score, passed)
print(students)
str(students)

The printout has a header with the three column names and a row number in front of every record. The function str shows a compact summary instead: the number of observations and variables, then each column with its type and the first values. The name column is character, score is numeric, and passed is logical, so the three types coexist in one object.

$ Rscript building.R
   name score passed
1   Ada    90   TRUE
2 Grace    85   TRUE
3  Alan    66  FALSE
'data.frame':	3 obs. of  3 variables:
 $ name  : chr  "Ada" "Grace" "Alan"
 $ score : num  90 85 66
 $ passed: logi  TRUE TRUE FALSE

Structure and dimensions

A data frame has two dimensions, unlike a plain list. The functions nrow and ncol return the number of rows and columns, dim returns both, and names returns the column names. The number of rows is also the length of every column.

df-structure.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66),
  passed = c(TRUE, TRUE, FALSE)
)
cat("rows:", nrow(students), "\n")
cat("columns:", ncol(students), "\n")
print(dim(students))
print(names(students))
print(class(students$score))

The table has three rows and three columns, and the column names are name, score, and passed. The class of a column is the class of the vector stored in it, which is numeric here. A data frame itself has class data.frame, and functions such as summary and plot use that class to choose the right behaviour.

$ Rscript df-structure.R
rows: 3 
columns: 3 
[1] 3 3
[1] "name"   "score"  "passed"
[1] "numeric"

Selecting columns

A data frame is a list, so a column can be reached in the same three ways as a list element. The dollar sign and the double bracket return the column vector itself. The single bracket with a name returns a data frame with one column, which is the form to use when the result must stay a table.

columns.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
print(students$name)
print(students[["score"]])
print(students["name"])
cat("single bracket is a data frame:", is.data.frame(students["name"]), "\n")

students$name and students[["score"]] return vectors, while students["name"] returns a one-column data frame, which is why the last line reports true. The distinction matters when the result is passed to another function: some functions accept a vector, others expect a table. Use the single bracket when the column count must be preserved.

$ Rscript columns.R
[1] "Ada"   "Grace" "Alan" 
[1] 90 85 66
   name
1   Ada
2 Grace
3  Alan
single bracket is a data frame: TRUE 

Selecting rows

Rows are selected with two subscripts separated by a comma: the row selector first, the column selector second. A blank selector means every row or every column. The row selector can be a number, a vector of numbers, or a logical vector, exactly as in the vector article.

rows.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
print(students[2, ])
print(students[students$score >= 80, ])
print(students[c(1, 3), c("name", "score")])

students[2, ] returns the second record with its original row number, two. The comparison students$score >= 80 produces a logical vector with one value per row, so the second selection keeps the two students who passed. The last line selects two rows and two columns at once and returns a smaller data frame.

$ Rscript rows.R
   name score
2 Grace    85
   name score
1   Ada    90
2 Grace    85
  name score
1  Ada    90
3 Alan    66

Adding and removing columns

Assignment with a new name adds a column, and assignment with an existing name replaces it. Assigning NULL removes the column. The recycling rule applies, so a single value fills every row and a shorter vector is repeated to the length of the table.

adding.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
students$passed <- students$score >= 70
students$rank <- 1:3
students$rank <- NULL
print(students)
str(students)

The new passed column is computed from score for every row in one expression. The rank column is added and then removed, so the final table has three columns again. Growing a data frame one column at a time is fine for small tables; for many columns it is better to build all the vectors first and call data.frame once.

$ Rscript adding.R
   name score passed
1   Ada    90   TRUE
2 Grace    85   TRUE
3  Alan    66  FALSE
'data.frame':	3 obs. of  3 variables:
 $ name  : chr  "Ada" "Grace" "Alan"
 $ score : num  90 85 66
 $ passed: logi  TRUE TRUE FALSE

Sorting rows

order returns the row positions that would put a column in order, and those positions are used as the row selector. The result is a reordered copy of the table, not an in-place sort. The row names travel with their rows, so the printed numbers no longer run from one upwards.

sorting.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan"),
  score = c(66, 90, 85)
)
ranked <- students[order(students$score, decreasing = TRUE), ]
print(ranked)
rownames(ranked) <- NULL
print(ranked)

Grace moves to the first row, Alan to the second, and Ada to the last. The row names 2, 3, and 1 show where each record came from; assigning NULL to rownames replaces them with a fresh sequence from one. To sort by several columns, pass several vectors to order; the later vectors break ties in the earlier ones.

$ Rscript sorting.R
   name score
2 Grace    90
3  Alan    85
1   Ada    66
   name score
1 Grace    90
2  Alan    85
3   Ada    66

Combining data frames

rbind stacks two tables that have the same columns, and cbind joins tables or vectors that have the same number of rows. Both functions return a new data frame. Row names are adjusted automatically when the sources would otherwise produce duplicates.

combining.R
first <- data.frame(name = c("Ada", "Grace"), score = c(90, 85))
second <- data.frame(name = "Alan", score = 66)
print(rbind(first, second))
print(cbind(first, passed = c(TRUE, TRUE)))

The first result appends Alan as the third row, and the second adds a logical column to the two-row table. Column names must match for rbind; a missing column is an error rather than a silent fill with missing values. For tables with different columns, merge them by a key instead.

$ Rscript combining.R
   name score
1   Ada    90
2 Grace    85
3  Alan    66
   name score passed
1   Ada    90   TRUE
2 Grace    85   TRUE

Merging by a key

merge combines two tables by one or more shared columns, called the key. The default is an inner join: only keys that appear in both tables survive. The argument all = TRUE performs an outer join and keeps every key, filling the missing side with NA.

merging.R
students <- data.frame(
  id = c(1, 2, 3),
  name = c("Ada", "Grace", "Alan")
)
scores <- data.frame(
  id = c(1, 2, 4),
  score = c(90, 85, 70)
)
print(merge(students, scores, by = "id"))
print(merge(students, scores, by = "id", all = TRUE))

The inner join keeps Ada and Grace, whose ids appear in both tables. The outer join also keeps Alan, who has no score, and the fourth score, which has no student. The by argument can name several columns, and the arguments all.x and all.y keep all rows of only the left or only the right table.

$ Rscript merging.R
  id  name score
1  1   Ada    90
2  2 Grace    85
  id  name score
1  1   Ada    90
2  2 Grace    85
3  3  Alan    NA
4  4  <NA>    70

A complete example

The next script selects the students who passed, orders them by score, and renumbers the rows. It is the usual sequence at the end of a small analysis: filter, sort, and clean the row names before printing. The original table is not modified, because every step stores its result in a new object.

report.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan", "Edsger"),
  score = c(90, 85, 66, 78),
  subject = c("math", "art", "math", "art")
)
passed <- students[students$score >= 70, ]
passed <- passed[order(passed$score, decreasing = TRUE), ]
rownames(passed) <- NULL
cat("passed:", nrow(passed), "of", nrow(students), "\n")
print(passed)

Three of the four students pass. Ada leads with 90, Grace follows with 85, and Edsger takes third place with 78. The subject column shows that the table keeps text next to numbers, which a matrix could not do without converting everything to one type. A data frame is therefore the default container for real data sets.

$ Rscript report.R
passed: 3 of 4 
    name score subject
1    Ada    90    math
2  Grace    85     art
3 Edsger    78     art

Next steps

The subsetting article treats the bracket operator in depth, including the drop argument and the subset convenience function. The missing values article shows how absent cells behave in a table, and the apply family article summarises columns without a loop. The tibbles article later in the series compares this base class with the tidyverse alternative.

Source

An Introduction to R: data frames

R documentation: data.frame

R documentation: merge

R documentation: extract or replace parts of an object

In this article we have built data frames from vectors and inspected their structure with str, nrow, and names. We selected columns with $, [[, and [, selected rows with numbers and logical conditions, added and removed variables, and sorted records with order. We stacked and joined tables with rbind and cbind, merged them by a key, and finished with a small filtered report. The series continues with R strings.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.