tutoring2

map 用法

Jiaxiang Li 2018-11-26

x=x

library(tidyverse)
## -- Attaching packages ------------------------------------------------------------------------------------------------------------------------------ tidyverse 1.2.1 --

## √ ggplot2 3.1.0     √ purrr   0.2.5
## √ tibble  1.4.2     √ dplyr   0.7.8
## √ tidyr   0.8.2     √ stringr 1.3.1
## √ readr   1.1.1     √ forcats 0.3.0

## -- Conflicts --------------------------------------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
spread <- list(sd = sd, iqr = IQR, mad = mad)
x <- rnorm(100)
invoke_map_dbl(spread, x = x)
##       sd      iqr      mad 
## 1.071393 1.381208 1.042040

参考 Community的这个答案, 注意函数invoke_map_dbl(.f = spread, .x = list(NULL), ...)

  1. 这里x = x指的是...,也就是其他参数。
  2. 当对.x不指定时,默认.x = list(NULL)

other

set.seed(123)
# 以下出现随机数,限定 seed
x <- rnorm(100)
library(purrr)
library(tidyr)
# invoke_map(spread, .x = x)

这里spread函数设定有问题,因为点开help文档,这里需要指定两个参数,keyvalue这里只有一列数据rnorm(100)

…中 x=x,为啥不是.x=x呢?我看这个函数的参数里是.x啊

purrr::invoke_map看 help 文档。

这说明这里是一组函数,因此这里不能单个用spread,注意list的格式,写成list(spread)

这里依然说明是一组数据,因此不能单个用rnorm(100),注意list的格式,写成list(rnorm(100))

为了跑通代码,我这里将函数spread替换成mean,你可以之后设置好list测试下。

invoke_map(list(mean),list(x))
## [[1]]
## [1] -0.5604756