purrr 是一個拓展R函數(shù)式編程能力的包。在這篇文章中朗兵,介紹在purrr中幾個非常實用的函數(shù)污淋。
purrr已經(jīng)集成在tidyverse中,所以如果已經(jīng)安裝了tidyverse的話則不需要重復(fù)安裝了余掖。
1. map 家族
1.1 map函數(shù)
library(purrr)
numbers <- list(11, 12, 13, 14)
map(numbers, sqrt)
得到的結(jié)果如下寸爆,返回一個列表
[[1]]
[1] 3.316625
[[2]]
[1] 3.464102
[[3]]
[1] 3.605551
[[4]]
[1] 3.741657
1.2 map_dbl函數(shù)
map_dbl(numbers, sqrt)
返回一個實數(shù)原子列表(atomic list)
[1] 3.316625 3.464102 3.605551 3.741657
1.3 map_if函數(shù)
map_if函數(shù)會對于list進行一個邏輯判斷,如果是真則執(zhí)行命令盐欺,否則不執(zhí)行而昨,保留原值。
#創(chuàng)造一個輔助函數(shù)找田,如果為偶數(shù)則返回TRUE
is_even <- function(x){
!as.logical(x %% 2)
}
map_if(numbers, is_even, sqrt)
[[1]]
[1] 11
[[2]]
[1] 3.464102
[[3]]
[1] 13
[[4]]
[1] 3.741657
1.4 map_at函數(shù)
map_at函數(shù)是給定位置向量,然后執(zhí)行命令着憨。
map_at(numbers, c(1,3), sqrt)
[[1]]
[1] 3.316625
[[2]]
[1] 12
[[3]]
[1] 3.605551
[[4]]
[1] 14
1.5 map2函數(shù)
map_2函數(shù)可以輸入2個參數(shù)墩衙,同時將兩個列表映射到一個函數(shù)中。
numbers2 <- list(1, 2, 3, 4)
map2(numbers, numbers2, `+`)
[[1]]
[1] 12
[[2]]
[1] 14
[[3]]
[1] 16
[[4]]
[1] 18
或者我們也可以使用pmap()函數(shù)將任意數(shù)量的列表映射到任何函數(shù)甲抖。
x <- list(1, 10, 100)
y <- list(1, 2, 3)
z <- list(5, 50, 500)
pmap(list(x, y, z), sum)
[[1]]
[1] 7
[[2]]
[1] 62
[[3]]
[1] 603
2.debug類函數(shù)
2.1 possibly函數(shù)
possibly()函數(shù)是即使報錯漆改,也要繼續(xù)執(zhí)行你的循環(huán),結(jié)合map使用可以在loop中不中斷循環(huán)准谚,當然這種功能也可以使用tryCatch函數(shù)挫剑。
possible_sqrt <- possibly(sqrt, otherwise = NA_real_)
numbers_with_error <- list(1, 2, 3, "spam", 4)
map(numbers_with_error, possible_sqrt)
[[1]]
[1] 1
[[2]]
[1] 1.414214
[[3]]
[1] 1.732051
[[4]]
[1] NA
[[5]]
[1] 2
2.2 safely函數(shù)
safely函數(shù)與possibly函數(shù)很相似,但是它會在列表中返回列表柱衔。因此元素是結(jié)果和伴隨錯誤消息的列表樊破。如果沒有錯誤愉棱,則返回NULL。如果有錯誤哲戚,則返回錯誤信息奔滑。個人覺得沒有possibly好用。
3. 累加操作
3.1 reduce函數(shù)
reduce(numbers, `*`)
[1] 24024
reduce函數(shù)非常常用顺少,你可以reduce任何東西朋其。