← Back to R Course | Chapter 7: Data Structures | Lesson 3 of 7

Data Frames

A data frame is a table like a spreadsheet, where each column holds one kind of information and each row is one case. It is the main way R keeps real-world data.

In this page:

  1. Data Frames
Syntax
r
df <- data.frame(column1 = c(value1, value2),
                 column2 = c(value3, value4))
df$column1
df[row, col]

Data Frames

A data frame is R's table-like structure for tabular data, where each column can have a different type but all columns have the same number of rows -- similar to a spreadsheet or SQL table.

It's created with data.frame() and is the primary structure used for data analysis in R. Columns are accessed with $ and rows/columns with [row, col] indexing.

Note: Use str(df) to quickly see a data frame's column names, types, and a preview of its values.

Example: Data Frames

markup
df <- data.frame(
  name = c("Alice", "Bob", "Cara"),
  age = c(30, 25, 40)
)

print(df)
cat("Ages:", df$age, "\n")
print(df[1, ])
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the comma when indexing, as in df[1], which returns a column as a data frame, while df[1, ] is the first row.
  2. Creating columns of different lengths, which fails with arguments imply differing number of rows.
  3. Expecting a string column to be a factor or vice versa, when since R 4.0 stringsAsFactors defaults to FALSE.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.