swirl包——R语言入门绝佳指引
在写这个之前,我想安利一波swirl包。
在这个信息爆炸的时代,我们要做的不是收集资料,而是做选择。
如果要用一个包来入门R,我会毫不犹豫的推荐swirl包。
install.packages('swirl')
require(swirl)
swirl() #开启swirl学习
0 #退出swirl
安装调用swirl包
开启swirl包的教程
R programming教程开始
dplyr
阅读官方文档https://cran.r-project.org/web/packages/dplyr/dplyr.pdf
dplyr is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges.
dplyr包主要用于数据框的数据处理。
安装并调用dplyr
install.packages('dplyr')
library(dplyr)
?dplyr
dplyr: a grammar of data manipulation
Description
dplyr provides a flexible grammar of data manipulation. It's the next iteration of plyr, focused on tools for working with data frames (hence thed in the name).
数据准备
nycflights13包中的flights作为example,安装调用。数据为2013年从纽约出发的336776次航班信息
解释一下列名含义:
day日期,dep_time起飞时间,sched_dep_time计划起飞时间,dep_delay起飞延误时间,arr_time到达时间,sched_arr_time计划到达时间,arr_delay到达延误时间,carrier航空公司缩写,flight航班,tailnum飞机尾号,origin出发地,dest目的地,
install.packages('nycflights13')
library(nycflights13)
flights
安装调用nycflights13包
筛选数据filter
#筛选11月30日的航班
filter(flights,month==11,day==30)
#筛选11、12月的航班
filter(flights,month %in% c(11,12))
筛选11月30日所有航班
筛选11月和12月两个月的航班
数据排列arrange
#数据框按照年、月、日的升序排列
arrange(flights,year,month,day)
#按照arr_delay降序排列
arrange(flights,desc(arr_delay))
数据排列
数据选择select
#按照年、月、日选择列
select(flights,year,month,day)
#选择年到日的列
select(flights,year:day)
#选择time_hour,air_time两个变量在前,其他的在后
select(flights,time_hour,air_time,everything())
数据排列
变形mutate
#数据集只保留新的变量a,a=arr_delay-dep_delay)
transmute(flights,a=arr_delay-dep_delay)
#在数据集的末尾添加新变量a,a=arr_delay-dep_delay
mutate(flights,a=arr_delay-dep_delay)
数据变形
分组group、概括summarize
#按照天分组
by_day<-group_by(flights,year,month,day)
#对每天的延误时间去均值,summarize针对分组进行运算
summarize(by_day,delay=mean(dep_delay,na.rm=T))
数据分组和概括
抽样sample
#随机无重复的取10行数据
sample_n(flights, 10)
#随机有重复的取50行数据
sample_n(flights, 50, replace = TRUE)
#随机无重复的以hour值做权重取10行数据
sample_n(flights, 10, time = hour)
随机抽样