data.frame 函数
7 methods用于创建和操作数据框的基础 R 函数。
length(x) -> integer从命名向量或列创建数据框,stringsAsFactors 默认为 FALSE。
Parameters
| Name | Type | Description |
|---|---|---|
| ... | any | 要合并的命名列(向量)。 |
Returns
integer
Example
r
x <- c(1, 2, 3, 4)
length(x) # 4
length(character()) # 0c(...) -> vector返回数据框或矩阵的行数。
Parameters
| Name | Type | Description |
|---|---|---|
| ... | any | 一个数据框或矩阵。 |
Returns
vector
Example
r
x <- c(1, 2, 3)
y <- c("a", "b", "c")
z <- c(x, 4, 5) # 1 2 3 4 5x[i] (subscript)返回数据框或矩阵的列数。
Parameters
| Name | Type | Description |
|---|---|---|
| i | integer|logical|character | 一个数据框或矩阵。 |
Returns
vector
Example
r
x <- c(10, 20, 30, 40)
x[2] # 20
x[c(1, 3)] # 10 30
x[x > 15] # 20 30 40
x[-1] # 20 30 40 (drop first)sort(x, decreasing = FALSE) -> vector从数据框中提取第 i 行和第 j 列。两者均可省略以选择全部。
Parameters
| Name | Type | Description |
|---|---|---|
| x | vector | 行索引或逻辑过滤器。 |
| decreasing | logical | 列索引或名称。 |
Returns
vector
Example
r
x <- c(3, 1, 4, 1, 5)
sort(x) # 1 1 3 4 5
sort(x, decreasing = TRUE) # 5 4 3 1 1unique(x) -> vector按名称从数据框中提取单个列,并将其作为向量返回。
Parameters
| Name | Type | Description |
|---|---|---|
| col | vector | 列名(不带引号)。 |
Returns
vector
Example
r
x <- c(1, 2, 2, 3, 3, 3)
unique(x) # 1 2 3rev(x) -> vector按行合并数据框或向量(垂直堆叠)。列必须匹配。
Parameters
| Name | Type | Description |
|---|---|---|
| ... | vector | 要按行合并的对象。 |
Returns
vector
Example
r
x <- c(1, 2, 3)
rev(x) # 3 2 1sum(..., na.rm = FALSE) -> numeric按列合并对象(并排)。行的长度必须匹配。
Parameters
| Name | Type | Description |
|---|---|---|
| ... | numeric | 要按列合并的对象。 |
| na.rm | logical | Remove NA values (default FALSE). |
Returns
numeric
Example
r
sum(1, 2, 3) # 6
sum(c(1, 2, NA)) # NA
sum(c(1, 2, NA), na.rm = TRUE) # 3