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:
Syntax
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
df <- data.frame(
name = c("Alice", "Bob", "Cara"),
age = c(30, 25, 40)
)
print(df)
cat("Ages:", df$age, "\n")
print(df[1, ])
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting the comma when indexing, as in
df[1], which returns a column as a data frame, whiledf[1, ]is the first row. - Creating columns of different lengths, which fails with
arguments imply differing number of rows. - Expecting a string column to be a factor or vice versa, when since R 4.0
stringsAsFactorsdefaults toFALSE.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: