参考:
tibbles
是一种不同于 data.frame
对象的数据框对象,特点是将字符向量转化为因子的形式。
1. R 或 RStudio 中安装所需要的包
# The easiest way to get tibble is to install the whole tidyverse:
install.packages("tidyverse")
# Alternatively, install just tibble:
install.packages("tibble")
# Or the the development version from GitHub:
# install.packages("devtools")
devtools::install_github("tidyverse/tibble")
# and then library
library(tidyverse) ## or library(tibble)
2. 创建 tibbles
2.1 已有 data.frame
结构的数据,可以直接使用as_tibble()
函数进行转换

2.2 自定义创建
t1 <- tibble(
x = 1:5,
y = 1,
z = x ^ 2 + y)
t1
t2 <- tibble(
`:)` = "smile",
` ` = "space",
`2000` = "number")
t2
t3 <- tribble(
~x, ~y, ~z,
#--|--|----
"a", 2, 3.6,
"b", 1, 8.5)
t3

3. tibbles vs. data.frame
区别主要在 printing 和 subsetting 方面
3.1 输出(printing)
tibble 结果显示前10行,如下:

使用
print()
函数,能够通过其中的 n
参数控制输出结果的行数, width
参数控制输出的列数:
设置
options()
:
options(tibble.print_max = n, tibble.print_min = m)
只输出 m 行如果有大于 n 行options(tibble.print_min = Inf)
显示所有行options(tibble.width = Inf)
显示所有列
3.2 提取子集(subsetting)
单一行列的提取
$
和[[
。
[[
can extract by name or position;$
only extracts by name but is a little less typing.
df <- tibble(
x = runif(5),
y = rnorm(5))
df
# Extract by name
df$x
df[["x"]]
# Extract by position
df[[1]]

如果加上
magrittr
的 pipe ,则需要用上 “ . ”:
df %>% .$x
df %>% .[["x"]]

4. 与 data.frame
进行转换:
as.data.frame()
as_tibble()
网友评论