purrr

 library(tidyverse)

dat = data.frame(y1 = rnorm(10),y2 = rnorm(10)+10)


re = list() #1

for(i in 1:2){ #2

  re[[i]] = mean(dat[,i]) #3


map(dat,mean)

map_dbl(dat,mean)

map_df(dat,mean)

map_df(dat,~mean(.))


iris %>% 

  split(.$Species) %>% 

  map(.,~aov(Sepal.Length ~ Sepal.Width,data=.) %>% summary)


# aov(Sepal.Length ~ Sepal.Width,data = iris)


mtcars %>% 

  split(.$cyl) %>% 

  map(.,~lm(mpg~wt+hp+drat,data = .)) %>% 

  map(coef) %>% 

  map_df('wt')


mtcars %>% 

  split(.$cyl) %>% 

  map(.,~lm(mpg~wt+hp+drat,data = .)) %>% 

  map(coef) %>% 

  as.data.frame()



x <- list(

  list(-1, x = 1, y = c(2), z = "a"),

  list(-2, x = 4, y = c(5, 6), z = "b"),

  list(-3, x = 8, y = c(9, 10, 11))

)


# select by name

map_dbl(x,'x')

# select by position

map_dbl(x,1)

# select by name and position

map_dbl(x,list('y',1))


wt <- c(5,  5,  4,  1)/15

x <- c(3.7,3.3,3.5,2.8)

weighted.mean(x, wt) 

# 3.7*0.3333+3.3*0.3333+3.5*0.2667+2.8*0.0667

# 等价于 

mean(x)


xs <- map(1:8,~runif(10))

xs[[1]][[1]] <- NA

ws <- map(1:8,~rpois(10,5) + 1)


map2_dbl(xs,ws,weighted.mean)

map2_dbl(xs,ws,weighted.mean,na.rm = T)

pmap(list(xs,ws),weighted.mean)

pmap(list(xs,ws),weighted.mean,na.rm = T)   # 非向量参数放在函数后面



l <- map(1:4, ~ sample(1:10,15,replace = T))

# reduce() 接收一个长度为 n 的向量输入,返回结果是长度为 1 的向量

# 利用 reduce 可以实现一行代码解决问题

reduce(l,intersect)


# l <- map(1:4, sample(1:10,15,replace = T))  # 将报错,因此 map 中直接使用非匿名函数,该函数只会调用一次

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理