Python网络爬虫与文本数据分析
在不少实际问题中有许多具有规律性的重复操作,因此在程序中就需要重复执行某些语句。
问题
比如有一个序列ns,现在想得到res,让ns中每一个数字变为平方数,代码如下
ns<-c(1,2,3,4,5,6,7,8,9,10)res<-c()for(ninns){res<-c(res,n*n)}res
##[1]149162536496481100
R语言tidyverse中的purrr包含三个向量化操作函数,如果熟悉Python的map会很容易理解R语言的purrr;求平方用purrr解决代码如下
library(purrr)#map(数据,操作函数)res<-map(ns,function(x)x*x)unlist(res)
##[1]149162536496481100
purrr包
purrr包是R语言中提高代码效率的包,常见的函数有
purrr::map(.x, .f) 对x实行f操作
purrr::map2(.x, y, .f) 对x和y实行f操作
purrr::pmap(.l, .f) 对多维列表l实行f操作
map计算年龄
library(tibble)infos<-tibble(family=c("张","李","王","赵"),name=c("三","四","五","六"),born=c(1990,1992,2000,1985))infos
计算年龄
age<-purrr::map(infos$born,function(x,y){-x})%>%unlist()infos$age<-ageinfos
map2拼接姓名
fullname<-purrr::map2(infos$family,infos$name,function(x,y)paste0(x,y))%>%unlist()infos$fullname<-fullnameinfos
pmap拼接姓名
上面所有的操作都使用的map和map2,现在使用pmap操作拼接姓名
infos<-tibble(family=c("张","李","王","赵"),name=c("三","四","五","六"),born=c(1990,1992,2000,1985))infos
fullname<-purrr::pmap(list(x=infos$family,y=infos$name),function(x,y)paste0(x,y))%>%unlist()infos$fullname<-fullnameinfos
R语言相关
R语言 | 读写txt、csv、excel文件R语言 | 数据操作tidyr包R语言 | 数据操作dplyr包R语言 | jiebaR中文分词包R语言 | 词频统计R语言 | 制作词云图后台回复关键词【purrr】获取本文代码和数据
“分享”和“在看”是更好的支持!
如果觉得《R语言 | 向量化操作purrr包》对你有帮助,请点赞、收藏,并留下你的观点哦!