data.frame functions
7 methodsBase R functions for creating and manipulating data frames.
data.frame(...) -> data.frameCreates a data frame from named vectors or columns, with stringsAsFactors defaulting to FALSE.
Parameters
| Name | Type | Description |
|---|---|---|
| ... | any | Named columns (vectors) to combine. |
Returns
data.frame
Example
df <- data.frame(
name = c("Ann", "Bob"),
age = c(25, 30)
)
# name age
# 1 Ann 25
# 2 Bob 30nrow(x) -> integerReturns the number of rows in a data frame or matrix.
Parameters
| Name | Type | Description |
|---|---|---|
| x | data.frame|matrix | A data frame or matrix. |
Returns
integer
Example
df <- data.frame(a = 1:3, b = 4:6)
nrow(df) # 3ncol(x) -> integerReturns the number of columns in a data frame or matrix.
Parameters
| Name | Type | Description |
|---|---|---|
| x | data.frame|matrix | A data frame or matrix. |
Returns
integer
Example
df <- data.frame(a = 1:3, b = 4:6)
ncol(df) # 2x[i, j] (subset)Extracts rows i and columns j from a data frame. Either may be omitted to select all.
Parameters
| Name | Type | Description |
|---|---|---|
| i | integer|logical | Row indices or logical filter. |
| j | integer|character | Column indices or names. |
Returns
data.frame|vector
Example
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 > 26x$col (column access)Extracts a single column by name from a data frame, returning it as a vector.
Parameters
| Name | Type | Description |
|---|---|---|
| col | character | Column name (unquoted). |
Returns
vector
Example
df <- data.frame(name = c("Ann", "Bob"), age = c(25, 30))
df$age # 25 30
df$name # "Ann" "Bob"rbind(...) -> data.frameCombines data frames or vectors by rows (stacking vertically). Columns must match.
Parameters
| Name | Type | Description |
|---|---|---|
| ... | data.frame|vector | Objects to row-bind. |
Returns
data.frame
Example
df1 <- data.frame(a = 1, b = 2)
df2 <- data.frame(a = 3, b = 4)
rbind(df1, df2)
# a b
# 1 1 2
# 2 3 4cbind(...) -> data.frameCombines objects by columns (side by side). Rows must match in length.
Parameters
| Name | Type | Description |
|---|---|---|
| ... | data.frame|vector | Objects to column-bind. |
Returns
data.frame
Example
df <- data.frame(a = 1:3)
cbind(df, b = 4:6)
# a b
# 1 1 4
# 2 2 5
# 3 3 6