【上一篇:87.关于map()函数系列】
【下一篇:89.关于safely()、possibly()和quietly()函数】
意会......
map()函数系列的shortcut
> models <- mtcars %>%
split(.$cyl) %>%
map(function(df) lm(mpg ~ wt, data = df))
. 代表当前元素
匿名函数:function(df) lm(mpg ~ wt, data = df)
> models <- mtcars %>%
split(.$cyl) %>%
map(~lm(mpg ~ wt, data = .))
. 代表列表的当前元素
单边公式:~lm(mpg ~ wt, data = .)
> models %>%
map(summary) %>%
map_dbl(~.$r.squared)
split(.$cyl)不加~是因为split()函数中的参数是factor而不是公式
.$cyl、.$r.squared是一个整体,加上~才是公式
> models %>%
map(summary) %>%
map_dbl("r.squared")
map_dbl函数的公式参数可以是character vector
与appy()族函数的比较
map()和lapply()是最相似的,输入都是Vector(List或atomic vetor),输出也全部是List。lapply()的FUN参数不能用单边公式和shortcut,而map()可以,因此后者的书写也更简简洁。
vapply()函数需要通过FUN.VALUE参数给定一个输出的模板(向量),而map()函数系列可以通过函数名中的类型直接输出对应数据类型的结果,例如:vapply(df, is.numeric, logical(1))等价于map_lgl(df, is.numeric)。vapply()可以输出matrices,而map()只能输出vector。
【上一篇:87.关于map()函数系列】
【下一篇:89.关于safely()、possibly()和quietly()函数】
网友评论