1108 chapter 16 purrr

迭代方式两种:命令式编程+函数式编程
永远不要复制粘贴超过2次

for循环

组成

  • 输出
    使用vector()函数,参数:向量类型(“logical”,“integer”,"double","character")+向量长度
    vector(“logical”/“integer”/"double"/"character"/"list", ncol(df)/length(vector))
  • 序列
    seq_along()
  • 循环体

p221练习题

  1. 不知道怎么开始每列的循环,select()可以选择。。
    || 答案:ncol()
    a.
output <- vector("double", ncol(mtcars))
names(output) <- names(mtcars)
for (i in names(mtcars)) {
  output[i] <- mean(mtcars[[i]])
}
output

b.确定数据类型? class()

  • 注意的是这里需要的不是一个向量,而是一个list,因为会有很多类型
data("flights", package = "nycflights13")
output <- vector("list", ncol(flights))
names(output) <- names(flights)
for (i in names(flights)) {
  output[[i]] <- class(flights[[i]])
}
output

c.

data("iris")
iris_uniq <- vector("double", ncol(iris))
names(iris_uniq) <- names(iris)
for (i in names(iris)) {
  iris_uniq[i] <- length(unique(iris[[i]]))
}
iris_uniq

d.

n <- 10
mu <- c(-10, 0, 10, 100)
normals <- vector("list", length(mu))
for (i in seq_along(normals)) {
  normals[[i]] <- rnorm(n, mean = mu[i])
}
normals
stringr::str_c(letters, collapse = "")

sd(x)

all.equal(cumsum(x),out)

a.

humps <- c("five", "four", "three", "two", "one", "no")
for (i in humps) {
  cat(str_c("Alice the camel has ", rep(i, 3), " humps.",
             collapse = "\n"), "\n")
  if (i == "no") {
    cat("Now Alice is a horse.\n")
  } else {
    cat("So go, Alice, go.\n")
  }
  cat("\n")
}

b.

numbers <- c("ten", "nine", "eight", "seven", "six", "five",
             "four", "three", "two", "one")
for (i in numbers) {
  cat(str_c("There were ", i, " in the bed\n"))
  cat("and the little one said\n")
  if (i == "one") {
    cat("I'm lonely...")
  } else {
    cat("Roll over, roll over\n")
    cat("So they all rolled over and one fell out.\n")
  }
  cat("\n")
}

c.

bottles <- function(i) {
  if (i > 2) {
   bottles <- str_c(i - 1, " bottles")
  } else if (i == 2) {
   bottles <- "1 bottle"
  } else {
   bottles <- "no more bottles"
  }
  bottles
}
beer_bottles <- function(n) {
  # should test whether n >= 1.
  for (i in seq(n, 1)) {
     cat(str_c(bottles(i), " of beer on the wall, ", bottles(i), " of beer.\n"))
     cat(str_c("Take one down and pass it around, ", bottles(i - 1),
                " of beer on the wall.\n\n"))
  }
  cat("No more bottles of beer on the wall, no more bottles of beer.\n")
  cat(str_c("Go to the store and buy some more, ", bottles(n), " of beer on the wall.\n"))
}
beer_bottles(3)

预先分配的更快

for循环变体

四种变体

  • 修改现有对象
  • 使用名称或者值进行迭代,而不使用索引
  • 处理未知长度的输出
  • 处理未知长度的序列
    [[,表明我们要处理的是单个元素

循环模式(三种)

  • 数值索引 for(i in seq_along(xs))
  • 元素进行循环 for(x in xs)
  • 名称进行循环 for(nm in names(xs))

未知输出长度

将结果保存在列表中,循环结束后再组合成单个向量

未知序列长度

while循环

for 循环和函数式编程

将函数作为参数传入另一个函数!!

映射函数

map(); map_lgl(), map_int(); map_dbl(); map_chr()
purrr()函数基本是用C实现的

R基础包

lapply(), sapply(), vapply()

p231练习题

  1. map_dbl(mtcars, mean)
    map_chr(nycflights13::flights, typeof)
    length(unique(iris$Species))
  2. map_lgl(iris, is.factor)
  3. 产生1个,2,3, 4,5个随机数

失败操作

safely(), error,result; possibly(),quietly(),

多参数映射

map2(),pmap(), invoke_map()

游走函数

walk(), pwalk(),walk2()d都会隐式地返回.x

for循环的其他模式

keep(),discard(),detect(),detect_index(), head_while(),tail_while(),
reduce()

p239练习题

3.如果没有选中列的话,会返回空列表,因为空列表不能使用[]

推荐阅读更多精彩内容