R - Functions apply, purrr
map(df/list, function), apply function to each of df, return a list. Iterate over columns of the dataframe df, or elements of the list.
map_dbl (lgl,int,chr) return a vector of specified types.
map is believed to be more consistent than the sapply, lapply.
Other ways to specify the function:
map(df, function(x) sum(is.na(x)) ), or
map(df, ~ sum(is.na(.)) )
Other shortcut:
Dealing with failures
map(df, safely(function here)) will return a list with all results (as normal) and errors (NULL or error report)
Other to try, possibly(), quietly()
Multi-dimension iteration
map2(list(5,10,20),list(1,2,3),rnorm) iterate over 2 args
pmap(list(n = list(5,10,20) , mean = list(1,2,3), sd = list(0.1,0.2,0.3) )) iterate over many args
invoke_map(list(func1,func2,func3), n = 5) iterate over funtions
Each has a family of functions, the _int _chr that return a vector with data types.
Maps for functions with side effects
Such as print,ggplot, save file
walk() – same usage as map
Comments
Post a Comment