map 函数
- map_家族
map() # 返回一个列表(list)
map_df() # 返回data.frame
map_lgl() # 返回一个逻辑型向量
map_int() # 返回一个整数型向量
map_dbl() # 返回双精度数值向量
map_chr() # 返回字符串向量
map_if()
如:
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
mtcars[,2:5]%>%map_if(is.factor,as.character,.else=as.integer)
![](https://img.haomeiwen.com/i15296946/168ddc05756e8556.png)
![](https://img.haomeiwen.com/i15296946/23c4ffa8c9a0199f.png)
- 类似于apply函数
df <- data.frame(a = c(1,2,3, NA), b = c(2,3,4,5), c = c(4,5,6,7))
df %>% map_dbl(median, na.rm = T)
df %>% map_df(median, na.rm = T)
apply(df, MARGIN = 2,median, na.rm = T)
![](https://img.haomeiwen.com/i15296946/412efce64259efea.png)
- 与function(){}自编函数连用
models <- mtcars %>% split(.$cyl) %>% map(function(df) lm(mpg ~ wt, data = df))
#简易写法
models <- mtcars %>% split(.$cyl) %>% map(~lm(mpg ~ wt, data = .))
coeff <- models %>% map(summary) %>% map_dbl(function(df) df$r.squared)
coeff <- models %>% map(summary) %>% map_dbl(~.$r.squared)
- map, map2 and pmap
x <- list(1, 10, 100)
y <- list(1, 2, 3)
z <- list(5, 50, 500)
df <- data.frame(a = c(1,2,3,4), b = c(2,3,4,5), c = c(4,5,6,7))
map(df,median)
map2(x,y,sum) # 这个是2个输入参数的函数
pmap(list(x, y, z), sum) # 需要放在list中
walk函数
plots <- mtcars %>% split(.$cyl) %>%
map(~ ggplot(data = ., aes(x = mpg, y = wt)) + geom_point())
name<- paste0(names(plots), ".pdf")
pwalk(list(name, plots), ggsave, path = "~/Documents/4.R语言/6. cookbook and ggplot2数据分析与图形艺术/1. Figure")
reduce and accumulate ----------------------
reduce函数采用“二进制”函数(即具有两个主输入的函数),并将其重复应用于列表,直到只剩下一个元素。
下面示例中full_join()就有两个主输入的函数。
dfs <- list(
age = tibble(name = "John", age = 30),
sex = tibble(name = c("John", "Mary"), sex = c("M", "F")),
trt = tibble(name = "Mary", treatment = "A")
)
dfs %>% reduce(full_join)
accumulate()与reduce()是类似的,但它保留了所有的中期结果。
f2<-function(x,y){x+y}
a = c(1,2,3,4)
reduce(a, f2)
res = accumulate(a, f2)
res
str(res)
网友评论