还是先
library(tidyverse)
#> ── Attaching packages ────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 3.0.0 ✔ purrr 0.2.5
#> ✔ tibble 1.4.2 ✔ dplyr 0.7.6
#> ✔ tidyr 0.8.1 ✔ stringr 1.3.1
#> ✔ readr 1.1.1 ✔ forcats 0.3.0
#> ── Conflicts ───────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag() masks stats::lag()
5.递归向量
- 创建
#创建原子向量-c()
x <- c(1, 2, 3)
#创建列表 list()
x <- list(1, 2, 3)
#查看列表结构
str(x)
#> List of 3
#> $ : num 1
#> $ : num 2
#> $ : num 3
- 可以包含不同类型的对象
y <- list("a", 1L, 1.5, TRUE)
str(y)
#> List of 4
#> $ : chr "a"
#> $ : int 1
#> $ : num 1.5
#> $ : logi TRUE
- 列表甚至可以包含其他列表
z <- list(list(1, 2), list(3, 4))
str(z)
#> List of 2
#> $ :List of 2
#> ..$ : num 1
#> ..$ : num 2
#> $ :List of 2
#> ..$ : num 3
#> ..$ : num 4
5.1列表取子集
a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -5))
- [] 提取子列表
str(a[1:2])
#> List of 2
#> $ a: int [1:3] 1 2 3
#> $ b: chr "a string"
str(a[4])
#> List of 1
#> $ d:List of 2
#> ..$ : num -1
#> ..$ : num -5
-[[]]或$提取元素 降低一个层级
str(a[[1]])
#> int [1:3] 1 2 3
str(a[[4]]) #和str(a[4])对比一下
#> List of 2
#> $ : num -1
#> $ : num -5
a$a
#> [1] 1 2 3
第六节应该是个超纲题!
6.特性
x <- 1:10
attr(x, "greeting") <- "Hi!"
attr(x, "farewell") <- "Bye!"
attributes(x)
#> $greeting
#> [1] "Hi!"
#>
#> $farewell
#> [1] "Bye!"
好像很抽象,结合?attr给出的例子和下面的重点。进行了一些摸索
#维度
attr(x,"dim") <- c(2, 5)
x
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 3 5 7 9
#> [2,] 2 4 6 8 10
#> attr(,"greeting")
#> [1] "Hi!"
#> attr(,"farewell")
#> [1] "Bye!"
#名称
y <- c(1,3,5)
attr(y,"names") <- c("a","b","c")
y
#> a b c
#> 1 3 5
#我成功的发现这就是命名操作,和之前讲的效果一样
set_names(c(1,3,5),c("a","b","c"))
#> a b c
#> 1 3 5
(难度好像真的超标,硬着头皮继续)
捋一下:
class控制泛型函数的运行方式
泛型函数允许根据不同类型的输入而进行不同的操作
那么字面翻译,泛型指的是多种输入类型。
7.扩展向量
(1)因子
x <- factor(c("ab", "cd", "ab"), levels = c("ab", "cd", "ef"))
typeof(x)
#> [1] "integer"
class(x) #曾以为class和typeof一样,看来是错了。
#> [1] "factor"
attributes(x)#不仅能展示levels还能展示class
#> $levels
#> [1] "ab" "cd" "ef"
#>
#> $class
#> [1] "factor"
看到时间就跳过,暗爽。
(3)tibble
tibble 是扩展的列表,有 3 个class: tbl_df、 tbl 和 data.frame。它的特性有 2 个:(列)
names 和 row.names。
tb <- tibble::tibble(x = 1:5, y = 5:1)
typeof(tb)
#> [1] "list"
关于tibble和data.frame
tb <- tibble::tibble(x = 1:5, y = 5:1)
typeof(tb)
#> [1] "list"
attributes(tb)
#> $names
#> [1] "x" "y"
#>
#> $row.names
#> [1] 1 2 3 4 5
#>
#> $class
#> [1] "tbl_df" "tbl" "data.frame"
df <- data.frame(x = 1:5, y = 5:1)
typeof(df)
#> [1] "list"
attributes(df)
#> $names
#> [1] "x" "y"
#>
#> $class
#> [1] "data.frame"
#>
#> $row.names
#> [1] 1 2 3 4 5
主要区别就是class!tibble里包含了data.frame。
网友评论