Skip to content

R data.frame API

R's data.frame — a tabular structure of rows and columns, the workhorse of base R data analysis.

1 class · 7 methods

data.frame functions

7 methods

Base R functions for creating and manipulating data frames.

data.frame(...) -> data.frame

Creates a data frame from named vectors or columns, with stringsAsFactors defaulting to FALSE.

Parameters

NameTypeDescription
...anyNamed columns (vectors) to combine.

Returns

data.frame

Example

r
df <- data.frame(
  name = c("Ann", "Bob"),
  age  = c(25, 30)
)
#   name age
# 1  Ann  25
# 2  Bob  30
nrow(x) -> integer

Returns the number of rows in a data frame or matrix.

Parameters

NameTypeDescription
xdata.frame|matrixA data frame or matrix.

Returns

integer

Example

r
df <- data.frame(a = 1:3, b = 4:6)
nrow(df)  # 3
ncol(x) -> integer

Returns the number of columns in a data frame or matrix.

Parameters

NameTypeDescription
xdata.frame|matrixA data frame or matrix.

Returns

integer

Example

r
df <- data.frame(a = 1:3, b = 4:6)
ncol(df)  # 2
x[i, j] (subset)

Extracts rows i and columns j from a data frame. Either may be omitted to select all.

Parameters

NameTypeDescription
iinteger|logicalRow indices or logical filter.
jinteger|characterColumn indices or names.

Returns

data.frame|vector

Example

r
df <- data.frame(name = c("Ann", "Bob"), age = c(25, 30))
df[1, ]          # first row
df[, "age"]      # age column as vector
df[df$age > 26, ]  # rows where age > 26
x$col (column access)

Extracts a single column by name from a data frame, returning it as a vector.

Parameters

NameTypeDescription
colcharacterColumn name (unquoted).

Returns

vector

Example

r
df <- data.frame(name = c("Ann", "Bob"), age = c(25, 30))
df$age  # 25 30
df$name # "Ann" "Bob"
rbind(...) -> data.frame

Combines data frames or vectors by rows (stacking vertically). Columns must match.

Parameters

NameTypeDescription
...data.frame|vectorObjects to row-bind.

Returns

data.frame

Example

r
df1 <- data.frame(a = 1, b = 2)
df2 <- data.frame(a = 3, b = 4)
rbind(df1, df2)
#   a b
# 1 1 2
# 2 3 4
cbind(...) -> data.frame

Combines objects by columns (side by side). Rows must match in length.

Parameters

NameTypeDescription
...data.frame|vectorObjects to column-bind.

Returns

data.frame

Example

r
df <- data.frame(a = 1:3)
cbind(df, b = 4:6)
#   a b
# 1 1 4
# 2 2 5
# 3 3 6