开始使用免费开始使用

让函数更加"purrr-fect"

我们还在改进一个函数,用来检测一组 URL 中是否包含不可用的元素。

先回顾一下目前的代码:

  • 通过组合 safely()map(.x, "error"),构建了一个错误抽取器。
  • 通过组合 safely()discard(.x, is.null),构建了一个"非 NULL"抽取器。
  • 通过使用 possibly(.x, otherwise = 404) 并将其封装为函数,构建了一个 404 生成器。

我们将稍微调整这个函数的行为:现在,您希望能够在返回结果或返回错误之间进行选择。

这样,您就可以用同一个函数回答两个问题:哪些 URL 无法访问?哪些 URL 可以访问?为此,您将为这个函数添加一个名为 "type" 的参数。

urls 向量和 safe_read() 已在您的工作区中可用。

本练习是课程的一部分

使用 purrr 的函数式编程进阶

查看课程

练习说明

完成函数定义。

  • safe_read() 映射到 URL 列表。
  • 将结果的名称设置为 URL 列表。
  • 将结果转置为包含 $result 和 $error 的列表。
  • 使用 pluck() 抽取 type 元素。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Complete the function definition
url_tester <- function(url_list, type = c("result", "error")) {
  type <- match.arg(type)
  url_list %>%
    # Apply safe_read to each URL
    ___(___) %>%
    # Set the names to the URLs
    ___(___) %>%
    # Transpose into a list of $result and $error
    ___()  %>%
    # Pluck the type element
    ___(___) 
}

# Try this function on the urls object
url_tester(urls, type = "error") 
编辑并运行代码