The fastest way to create a table in R depends on what you already have

If you have data in a vector or a data frame, the table() function builds a frequency table in one line. If you need to organize raw data into rows and columns first, data.frame() creates a table-like structure. If you want a polished table for reports or documents, knitr::kable() or gt package functions format it for display. The choice depends on whether you are counting occurrences, storing structured data, or preparing output for someone else to read.

Each method serves a different purpose in your workflow. You might use table() to explore a single variable, data.frame() to organize your working dataset, and kable() or gt() only when you are ready to share results.

Key Takeaways

  • The table() function counts how many times each value appears in a vector and returns a frequency table.
  • The data.frame() function organizes vectors of equal length into a table with named columns and rows.
  • The knitr::kable() function converts a data frame into a formatted table suitable for reports, PDFs, or HTML documents.
  • The gt package lets you build publication-quality tables with colors, borders, and custom formatting without writing HTML.

Using table() to count occurrences in a vector

The table() function is the simplest way to create a frequency table. Give it a vector, and it counts how many times each unique value appears. For example, if you have a vector of survey responses, table() tells you how many people chose each answer.

Here is the basic syntax:

responses <- c("yes", "no", "yes", "maybe", "no", "yes") table(responses)

This returns a table showing "yes" appears 3 times, "no" appears 2 times, and "maybe" appears 1 time. The output is a named vector with class "table", which R displays as a simple frequency count. You can also use table() with two or more vectors to create a cross-tabulation — a table showing how two variables relate to each other.

gender <- c("M", "F", "M", "F", "M") response <- c("yes", "no", "yes", "yes", "no") table(gender, response)

This creates a two-way table with gender in rows and response in columns, showing the count at each combination. Cross-tabulations are useful for seeing patterns between two categorical variables at a glance.

Using data.frame() to organize data into columns and rows

When you want to store related data together — not just count occurrences, but actually organize multiple variables — use data.frame(). A data frame is R's version of a spreadsheet: each column is a variable, each row is an observation, and all columns must have the same length.

Here is how to create one:

students <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(20, 21, 19), gpa = c(3.8, 3.5, 3.9) )

This creates a table with three rows and three columns. Each vector becomes a column, and the names you assign become the column headers. You can access a single column with the $ operator — for example, students$name returns just the names. You can also access rows and columns using square brackets: students[1, ] returns the first row, and students[ , 2] returns the second column.

Data frames are the foundation of most data analysis in R. Once you have data in a data frame, you can filter it, sort it, calculate summaries, and pass it to plotting or modeling functions. They are also the format that most R functions expect when you are doing statistical analysis or visualization.

Using knitr::kable() to format tables for reports

If you are writing a report in R Markdown or Quarto and want your table to look polished, knitr::kable() converts a data frame into a formatted table. It works in HTML, PDF, and Word documents.

First, load the knitr package (it usually comes with R Markdown), then pass your data frame to kable():

library(knitr) kable(students, caption = "Student Information")

This renders the table with borders, aligned columns, and a caption. You can control alignment with the align argument — for example, align = c("l", "c", "r") aligns the first column left, the second center, and the third right. You can also rename columns on the fly with the col.names argument.

kable(students, col.names = c("Name", "Age", "GPA"), align = c("l", "c", "c"))

For more control over appearance — colors, fonts, borders, and cell-level formatting — the gt package is more powerful, but kable() is faster for simple, clean tables that you need to produce quickly.

Using the gt package for publication-quality tables

The gt package (short for "grammar of tables") lets you build tables with fine-grained control over every element. You can add colors, custom fonts, footnotes, and conditional formatting without writing HTML.

Here is a basic example:

library(gt) gt(students) |> tab_header(title = "Student Roster") |> fmt_number(columns = gpa, decimals = 2)

This creates a table with a header, formats the GPA column to show exactly two decimal places, and uses the pipe operator |> to chain operations. You can add a subtitle with tab_subtitle(), highlight rows or cells with tab_style(), and add footnotes with tab_footnote(). The gt package is especially useful when you are creating tables for presentations, reports, or web pages where appearance matters and you want fine control over styling.

Converting between table types

Sometimes you create a table one way and need to convert it to another. If you have a frequency table from table() and want to turn it into a data frame, use as.data.frame():

freq_table <- table(responses) freq_df <- as.data.frame(freq_table)

This converts the frequency table into a two-column data frame: one column for the values and one for the counts. You can then format it with kable() or gt() for display. Similarly, if you have a data frame and want to create a frequency table from one of its columns, pass that column to table(): table(students$age). These conversions let you move between formats depending on what you need to do next.

Frequently Asked Questions

What is the difference between table() and data.frame()?

table() counts occurrences of values in a vector and returns a frequency table. data.frame() organizes multiple vectors into a structured table where each column is a variable and each row is an observation. Use table() for summaries; use data.frame() for storing and analyzing raw data.

Can I save a table I created in R to a file?

Yes. Use write.csv() to save a data frame as a CSV file: write.csv(students, "students.csv"). Use write.table() for other formats. If you created a formatted table with kable() or gt() in an R Markdown document, knit the document to HTML or PDF to save the formatted output.

How do I add or remove rows and columns from a data frame?

Add a column with df$new_column <- values or use cbind() to bind columns together. Add rows with rbind(). Remove a column by setting it to NULL: df$column <- NULL. Remove rows by subsetting: df[-row_number, ] removes that row.

What if my vectors have different lengths when I try to create a data frame?

R will return an error because all columns in a data frame must have the same number of rows. Make sure each vector has the same length before passing them to data.frame(). If one vector is shorter, you can repeat its values with rep() to match the length of the others.