R Handbook (Syntax) - purrr

purrr : A functional programming(FP) toolkit for R

Apply Functions

map(.x, .f, ...) Apply a function to each element of a list or vector
map2(.x,.y,.f,…) Apply a function to pairs of elements from two lists
pmap(.x, .f, ...) Apply a function to groups of elements from list of lists
imap(.x, .f, ...) Apply a function to each element of a vector, and its index
invoke_map(.f, .x = list(NULL) ) 调用不同的函数
walk(.x, .f), walk2(), pwalk() 并行处理

map_if(.x, .p, .f, ...) map_at(.x, .at, .f, ...) Other series with the map

Parameters:

.f: A function, Formula, or Atomic Vector
: Other parameters ( .xas having been ...specified first parameter)

.f parameter:

functionas.character %>% map(iris)

formula~ .xbecomes function(x)
map(l, ~ 2 +.x)
~ .x .y becomes function(.x, .y), e.g.
character
map(x,"y")becomes x[["y"]]
map(x,c("a","b")) becomes x[["a"]][["b"]]
integer
map(x,2) becomes x[[2]]

Output

function returns
map list
map_chr character vector
map_dbl double (numeric) vector
map_df data frame(auto)
map_dfc data frame (column bind)
map_dfr data frame (row bind)
map_int integer vector
map_lgl logical vector
walk Return type specified

map2, pmap, imap, invoke_map series with the map function

Examples:

1:10 %>%
 map(rnorm, n = 10) %>%
 map_dbl(mean)
 
tribble(mean=c(5,10,3),sd=c(1,5,3),n=c(2,3,8)%>%
  pmap(rnorm) #生成三组不同参数的正态分布

df <- tibble(
  f = c("runif", "rpois", "rnorm"),
  params = list(
    list(n = 10),
    list(n = 5, lambda = 10),
    list(n = 10, mean = -3, sd = 10))
)
invoke_map(df$f, df$params)

`list(1,"a",3)%>% walk(print)` #并行打印

Work with Lists

filter lists Explanation
pluck(.x, …, .default=NULL) Filter by name or indexx, pluck(x,"b")
keep(.x, .p, …)
discard(.x, .p, …)
Logical value screened keep(x, is.na)
negative results keep thediscard(x, is.na)
compact(.x, .p = identity) Delete empty element
head_while(.x, .p, …)
tail_while
Find all head / tail meet the values ​​match
logic Explanation
every(.x, .p, …)
some(.x, .p, …)
Each / some element in the list meets the requirements (returns a FALSE / TRUE)
mtcars %>% some(is_numeric)
has_element(.x, .y) The list contains one elementhas_element(x, "foo")
detect(.x, .f, …, .right=FALSE,.p)
detect_index(.x, .f, …, .right= FALSE, .p)
Returns TRUE first determines the element detect(x, is.character)
returns the index
vec_depth(x) Return depth(number of levels of indexes)
reshape lists Explanation
flatten(.x) The list of reduced dimension
flatten_lgl(), flatten_int(), flatten_dbl(), flatten_chr()
flatten_df,flatten_dfr(),flatten_dfc()
Returns a vector of
return data.frame
transpose(.list, .names = NULL) Transpose a list
simplify(.x, .type = NULL) Forced into a vector list
simplify_all(.x, .type = NULL)
combine Explanation
append(x, values, afer =length(x)) Adding at the tailappend(x, list(d = 1))
prepend(x, values, before =1) Starting addedprepend(x, list(d = 1))
splice(…) Into one list

Reduce Lists

Recursion Explanation
reduce(.x,.f,…init) .X recursive sub-element, returns a single value
.xlist or vector atoms,
initstart to accumulate the first value
reduce_right(.x,.f,…init) From right to left recursion
reduce2(.x, .y, .f, …, .init)
reduce2_right(.x, .y, .f, …, .init)
Three Parameters recursive
accumulate(.x, .f, …, .init) 将.x的子元素递归,返回中间值
accumulate_right(.x, .f, …, .init) 从右往左递归
list(data1,data2,data3) %>% 
   reduce(left_join,by = c("first","last"))

Debug

调试 说明
safely(.f, otherwise = NULL, quiet = TRUE) return list of results and errors
quietly(.f) return list of results, output, messages, warnings.
possibly(.f, otherwise, quiet = TRUE) continue with default value (instead of error) and return list of results,error
base::stop(message) stop and return message
base::stopifnot(logit1,logit2,logit3…) 检查每个参数为TRUE,否则停止执行当前表达式返回message

Work with Tibbles

Nested Data

nest

tidyr::nest(data, ..., .key = data)
For grouped data, moves groups into cells as data frames.

n_iris <- iris %>% group_by(Species) %>% nest()

tidyr::unnest(data, ..., .drop = NA, .id=NULL, .sep=NULL)
Unnests a nested data frame.

n_iris %>% unnest()

List Column Workflow

# step 1 Make a list column
n_iris <- iris %>%
 group_by(Species) %>%
 nest()

# step 2 Work with list columns
mod_fun <- function(df)
 lm(Sepal.Length ~ ., data = df)
m_iris <- n_iris %>%
 mutate(model = map(data, mod_fun))
 
# step 3 Simplify the list column
b_fun <- function(mod)
 coefficients(mod)[[1]]
m_iris %>% transmute(Species,
 beta = map_dbl(model, b_fun))
发布了101 篇原创文章 · 获赞 154 · 访问量 7万+

Guess you like

Origin blog.csdn.net/qq_41518277/article/details/102629067