神器purrr包是Hadley Wickham大神编写的高级函数编程语言包,它可以填充R功能性编程中的缺失部分,使得你的编程更加函数化。
purrr包提供了大量的类似map的函数。可以服务于减少循环、处理嵌套数据、多模型等应用需求。
map()函数
library("purrr") #加载包
data(mtcars) #使用数据集mtcars
head(mtcars) #查看mtcars数据的前五行
dim(mtcars) #查看数据mtcars的维度
##求mtcars数据的均值
map_dbl(mtcars, mean)
mtcars %>% map_dbl(mean)
##对mtcars的数据进行标准化
mtcars %>% map(function(x) (x - mean(x)/max(x)-min(x))) # list
mtcars %>% map_df(function(x) (x - mean(x)/max(x)-min(x)))# data.frame
map2()
n <- list(4,5,6)
m <- list(1,2,3)
map2(m,n, `+`)
by_cyl <- mtcars %>% split(.$cyl)
mods <- by_cyl %>% map(~ lm(mpg ~ wt, data = .))
map2(mods, by_cyl, predict)
pmap()
x <- list(1, 10, 100)
y <- list(1, 2, 3)
z <- list(5, 50, 500)
pmap(list(x, y, z), sum)
pmap(list(x, y, z), function(a, b ,c) a / (b + c))
accumulate() # 行列长度不变
mtcars[1,]
mtcars[1,] %>% accumulate(`+`) # 从左向右
mtcars[1,] %>% accumulate(`*`)
mtcars[1,] %>% accumulate_right(`+`) # 从右向左
mtcars[1,] %>% accumulate_right(`*`)
reduce () # 获得一个值
mtcars[,1]
mtcars[,1] %>% reduce(`+`) # 从左向右
mtcars[,1] %>% reduce(`*`)
mtcars[,1] %>% reduce_right(`+`) # 从右向左
mtcars[,1] %>% reduce_right(`*`)
detect () # 找到第一个匹配的值
mtcars[2,]
mtcars[2,] %>% detect(~. >50)
# detect_index() 并返回它的位置
mtcars[2,] %>% detect_index(~. >50)
some() 列表中的某些元素是否满足要求? 返回结果TRUE/FALSE
every() 列表中的每个元素是否满足要求?
mtcars %>% some(is_numeric)
mtcars %>% some(is_character)
mtcars %>% every(is_numeric)
mtcars %>% every(is_character)
x <- list(1:5,'R','ruby','python')
x %>% every(is_character)
x %>% some(is_character)
x %>% every(is_numeric)
x %>% some(is_numeric)