Skip to content

R base vector API

R 的 data.frame —— 一种由行和列组成的表格结构,是基础 R 数据分析的主力工具。

1 class · 7 methods

data.frame 函数

7 methods

用于创建和操作数据框的基础 R 函数。

length(x) -> integer

从命名向量或列创建数据框,stringsAsFactors 默认为 FALSE。

Parameters

NameTypeDescription
...any要合并的命名列(向量)。

Returns

integer

Example

r
x <- c(1, 2, 3, 4)
length(x)  # 4
length(character())  # 0
c(...) -> vector

返回数据框或矩阵的行数。

Parameters

NameTypeDescription
...any一个数据框或矩阵。

Returns

vector

Example

r
x <- c(1, 2, 3)
y <- c("a", "b", "c")
z <- c(x, 4, 5)  # 1 2 3 4 5
x[i] (subscript)

返回数据框或矩阵的列数。

Parameters

NameTypeDescription
iinteger|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

NameTypeDescription
xvector行索引或逻辑过滤器。
decreasinglogical列索引或名称。

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 1
unique(x) -> vector

按名称从数据框中提取单个列,并将其作为向量返回。

Parameters

NameTypeDescription
colvector列名(不带引号)。

Returns

vector

Example

r
x <- c(1, 2, 2, 3, 3, 3)
unique(x)  # 1 2 3
rev(x) -> vector

按行合并数据框或向量(垂直堆叠)。列必须匹配。

Parameters

NameTypeDescription
...vector要按行合并的对象。

Returns

vector

Example

r
x <- c(1, 2, 3)
rev(x)  # 3 2 1
sum(..., na.rm = FALSE) -> numeric

按列合并对象(并排)。行的长度必须匹配。

Parameters

NameTypeDescription
...numeric要按列合并的对象。
na.rmlogicalRemove 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