《R数据科学》|| 1-3章ggplot2与dplyr探索

r4ds

迷茫的日子里也不能忘了要学习新知识技能以及总结归纳啊。最近开始学习《R数据科学》中文版,这确实是本好书,有些知识点的层次关系及解释让我明白了许多之前对R一知半解的地方。以接下来的一系列笔记来归纳建立自己的知识体系,并一起分享交流学习。

第一章: 使用ggplot2进行数据可视化

  1. ggplot(),在此函数种添加的映射会作为全局变量应用到图中的每个几何对象种。

  2. 图层geom_point点图层

  3. 映射数据为图形属性 mapping=aes(),要想将图形属性映射为变量,需要在函数aes()中将图形属性的名称和变量的名称关联起来。

  4. 标度变化:将变量(数据)分配唯一的图形属性水平。

  5. 手动设置图形属性,此是在geom_point()层面。此时,这个颜色是不会传达变量数据的信息。

  6. 分层facetfacet_grid()可以通过两个变量对图分层`facet_grid(drvcyl)或(.cyl)

  7. 分组aes(group)此种按照图形属性的分组不用添加图例,也不用为几何对象添加区分特征

  8. 统计变换:绘图时用来计算新数据的算法称为stat(statistical transformation,统计变化)。比如对于geom_bar()默认是只对一个数据x映射,其统计变化后生成数据x种的每个值的count数。

    • 每个几何对象函数都有一个默认的统计变换,每个统计变换函数都有一个默认的几何对象。
    • 如需要展示二维数据,geom_bar(mapping=aes(x=a,y=b),stat="identity ")
  9. 图形属性/位置调整

    • color,fill
    • 位置调整参数position有三个选项:"identity","fill","dodge"
    • position="dodge"参数可分组显示数据,将每组种的条形依次并列放置,可以轻松比较每个条形表示的具体数值。
    • 数据的聚集模式无法很好确定,因为存在数据的过绘制问题(很多彼此十分仅的点重叠了)position="jitter"对于geom_position()函数来说,jitter的位置方式为抖动会排除过绘制问题
  10. 坐标系

    • coord_flip()函数可以交换x轴和y轴
    • labs():modify axis, legend, and plot labels.
mpg
str(mpg)
data<- mpg
?mpg ##查看mpg数据的说明
ggplot(data = mpg)+geom_point(aes(x=displ,y=hwy))

ggplot(mpg)+geom_point(mapping = aes(x=displ,y=hwy,color=class),color="#EF5C4E",shape=19)
ggplot(mpg)+geom_point(mapping = aes(x=displ,y=hwy),color="#EF5C4E",shape=19)
ggplot(mpg)+geom_point(mapping = aes(x=displ,y=hwy,stroke=displ),shape=19)
## 添加两个图层:geom_point,geom_smooth()
ggplot(mpg)+geom_point(mapping = aes(x=displ,y=hwy,color=drv))+geom_smooth(mapping = aes(x=displ,y=hwy,linetype=drv,color=drv))
# 添加分组
ggplot(data = mpg)+geom_smooth(mapping = aes(x=displ,y=hwy,group=drv))
ggplot(data = mpg)+geom_smooth(mapping = aes(x=displ,y=hwy,color=drv),show.legend = F) ## 图例 show.legend=F

## 在不同的图层中添加指定不同的数据
## data=filter(mpg,class=="suv"), se=F,表示去除f波动的范围。
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point(mapping = aes(color=class))+geom_smooth(data = filter(.data = mpg,class=="suv"))

##exercices
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point()+geom_smooth(se = F)
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point()+geom_smooth(se = F,mapping = aes(group=drv))
ggplot(data = mpg,mapping = aes(x=displ,y=hwy,color=drv))+geom_point()+geom_smooth(se = F)
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point(mapping = aes(color=drv))+geom_smooth(se = F)
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point(mapping = aes(color=drv))+geom_smooth(mapping = aes(linetype=drv),se = F)
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point(mapping = aes(color=drv))

### 统计变换
ggplot(data = mpg,mapping = aes(x=displ,y=hwy))+geom_point()+geom_smooth(se = F)
ggplot(data=diamonds)+stat_summary(mapping = aes(x=cut,y=depth))
ggplot(data=diamonds)+geom_boxplot(mapping = aes(x=cut,y=price))
ggplot(data=diamonds)+geom_bar(mapping = aes(x=cut))
ggplot(data=diamonds)+geom_bar(mapping = aes(x=cut,y=..prop..),group=2)

### 图形调整,位置调整
ggplot(diamonds)+geom_bar(mapping = aes(x=cut,fill=cut),color="black")+scale_fill_brewer(palette = "Set3")
ggplot(diamonds)+geom_bar(mapping = aes(x=cut,fill=clarity))+scale_fill_brewer(palette = "Set2")
ggplot(diamonds)+geom_bar(mapping=aes(x=cut,color=clarity),position = "dodge")+scale_fill_brewer(palette = "Set2")
ggplot(mpg)+geom_point(mapping = aes(x=displ,y=hwy),position = "jitter")
##exercises
ggplot(mpg,mapping = aes(x=cty,y=hwy))+geom_point(position = "jitter")+geom_smooth(color="black")
ggplot(mpg,mapping = aes(x=cty,y=hwy))+geom_jitter()
ggplot(mpg,mapping = aes(x=cty,y=hwy))+geom_count()
ggplot(mpg)+geom_boxplot(mapping = aes(x=manufacturer,y=hwy),position = "identity")
?geom_boxplot

###1.9 坐标系
ggplot(mpg,mapping = aes(x=class,y=hwy))+geom_boxplot()+coord_flip()
nz <- map_data("nz")
?map_data
ggplot(data=diamonds)+geom_bar(mapping = aes(x=cut,fill=cut),show.legend = FALSE)+theme(aspect.ratio = 1)+labs()
bar+scale_color_brewer(palette = "Set2")
bar+coord_flip()
bar+coord_polar()

第二章:工作流:基础 Workflow:basics

  1. 赋值:小技巧,alt+减号会自动输入赋值符号<- 并在前后加空格
  2. 对象:用snake_case命名法小写字母,以_分割。
  3. Rstudio中快捷查看命令:Alt+Shift+K

第三章:使用dplyr进行数据转换

  1. 特殊的data.frametibble
  2. 变量variable类型:
    • int:
    • dbl(num的一种?):双精度浮点数变量,或称实数。
    • chr:字符向量/字符串
    • dttm:日期+时间
    • lgl:逻辑型变量
    • fctr(factor):因子
    • date:日期型变量
  3. 基础函数:filter(),arrange(),select(),mutate(),summarize(),group_by()
  4. 使用filter()筛选:
    • filter(flights, arr_delay<=10).
    • 比较运算符 ==, !=, <=
    • 逻辑运算符 x & !y, x|y, xor(x,y)
    • 缺失值 NA, is.na()
## filter()
(jan1 <- filter(flights,month==1,day==1))
(dec25 <- filter(flights,month==12,day==25))
filter(flights,month>=11)
(nov_dec <- filter(flights,month %in% c(11,12)))
filter(flights,!(arr_delay<=120 | dep_delay<=120))
NA>=10
x <- NA
is.na(x)
df <- tibble(x=c(1,NA,2))
filter(df,x>1)
filter(df,is.na(x)|x>1)
### exercise
filter(flights,carrier %in% c("UA","AA","DL"))
filter(flights,month %in% c(7,8,9))
filter(flights,arr_delay>120 & dep_delay==0)
filter(flights,dep_delay >= 60 & (dep_delay-arr_delay>=30)) 
filter(flights,dep_time ==2400| dep_time<=600)
filter(flights,is.na(dep_time))


  1. 使用 arrange()按照列(variable)的值进行排序
    • desc倒序
    • 缺失值排在最后,若想提前可desc(is.na())
# arrange()
arrange(flights,desc(dep_delay,arr_delay)) #降序排列
arrange(flights,desc(is.na(dep_delay),arr_delay)) ##将NA值排列到前面

  1. 使用select()选择列:(数据集会有成千上万个变量,select选出变量的子集)
    • 选出year~day之间的列:select(flights, year:day)
    • 选出排除year~day列:select(flights,-(year:dat))
    • 匹配变量中的名称:starts_with(""), ends_with(), matches("")
    • rename()对列重新命名
    • everything()辅助函数来将某几列提前。
## select()
select(flights,year:day)
select(flights,-(year:day)) ## 不包括year:day
select(flights,starts_with("s"))
select(flights,ends_with("e"))
select(flights,matches("time"))
select(flights,matches("(.)\\1"))

rename(flights,tail_num=tailnum) ##对变量进行重命名
select(flights,-(month:day),everything()) ## 结合everything()辅助函数 对某几列提前, 置后同理
select(flights, hour:time_hour,everything())
###exercise
select(flights,year,year,year)
select(flights,one_of(c("year","month","day","dep_delay")))
select(flights,contains("TIME"))

  1. 使用mutate()添加新的列/变量:
    • mutate() 新列添加到已有列的后面;
    • transmute 只保留新的变量。
    • 常用的运算符号:求整%/%,求余%%,偏移函数lead(), lag(),累加和和滚动聚合,逻辑比较,排秩。
# mutate() 在tibble后 添加新变量/列
flights_sml <- select(flights,year:day,matches("_delay"),distance,air_time)
flights_sml
mutate(flights_sml,flying_delay=arr_delay-dep_delay,speed=distance/air_time * 60 )
flights_sml
transmute(flights,gain=arr_delay-dep_delay,hour=air_time/60,gain_per_hour=gain/hour)

mutate(flights,dep_time=((dep_time%/%100 * 60)+(dep_time%%100))) ## 会直接在flights中改动dep_time
flights
transmute(flights,air_time,duration=(arr_time-dep_time),arr_delay)
1:3+1:10
1:10+1:3
1:10
?cos
  1. 使用summarize()进行分组摘要:
    • group_by一起使用,将整个数据集的单位缩小为单个分组。
# 使用summarize()进行分组摘要
by_year <- group_by(flights,year,month)
summarise(by_year,delay=mean(arr_delay-dep_delay,na.rm = T))
####查看
(delay_byDay <- group_by(flights,month) %>%summarise(delay_time=mean(dep_delay,na.rm = T))) %>% ggplot(mapping = aes(x=month,y=delay_time))+geom_point()+geom_smooth(se=F)

  1. 利用管道符%>%对数据综合操作:
    • 综合就是flights %>% group_by(~) %>% summarize(mean(~~,na.rm=T)) %>% filter(~) %>% ggplot(aes())+geom_~()
    • 缺失值:na.rm=T,缺失值计算会都变成缺失值,可利用filter(!is.na(dep_delay),!is.na(arr_delay))
    • 常用的摘要函数:n()/sum()/mean()
    • 中位数median(),分散程度sd()/IQR()/mad()
    • 计数 n(),计算唯一值的数量n_distinct()去重复后唯一值的计数,count()可快速的计算。
    • 逻辑值的计数 和 比例summarize(n_early=sum(dep_time<50)),sum找出大于x的True的数量,mean会计算比例。
# 使用summarize()进行分组摘要
by_year <- group_by(flights,year,month)
summarise(by_year,delay=mean(arr_delay-dep_delay,na.rm = T))
####查看
(delay_byDay <- group_by(flights,month) %>%summarise(delay_time=mean(dep_delay,na.rm = T))) %>% ggplot(mapping = aes(x=month,y=delay_time))+geom_point()+geom_smooth(se=F)

### 使用管道组合多种操作
(delay_by_dest <- group_by(flights,dest)%>%summarise(count=n(),delay_time=mean(dep_time,na.rm = T), dist=mean(distance,na.rm = T))) %>% filter(count>20,dest!="HNL") %>% ggplot(mapping = aes(x=dist,y=delay_time))+geom_point(aes(size=count))+geom_smooth(se=F,color="darkblue")

## 管道符 %>%
(delay <- summarise(by_dest,count=n(),dist=mean(distance,na.rm = T),delay=mean(arr_delay,na.rm = T))) ### count=n()统计分组,就是dest城市的个数
delay <- filter(delay,count>20,dest!="HNL")## 筛掉飞行记录少的,特殊机场
ggplot(data = delay,mapping = aes(x=dist,y=delay))+geom_point(aes(size=count),alpha=1/3)+geom_smooth(se=F,color="darkblue")
(delay_by_dest <- group_by(flights,dest)%>%summarise(count=n(),delay_time=mean(dep_time,na.rm = T), dist=mean(distance,na.rm = T))) %>% filter(count>20,dest!="HNL") %>% ggplot(mapping = aes(x=dist,y=delay_time))+geom_point(aes(size=count))+geom_smooth(se=F,color="darkblue")
##查看飞机型号与延误时间的关系
flights %>% group_by(tailnum) %>%summarise(count=n(),delay_time=mean(arr_delay,na.rm = T)) %>%arrange(delay_time) %>%ggplot(mapping = aes(x=delay_time))+geom_freqpoly(binwidth = 10)
##查看航班数量 与 飞机延误时间的关系:航班数量少时,平均延误时间的变动特别大
delay_time %>% filter(count>25) %>% ggplot(mapping = aes(x=count,y=delay_time))+geom_point(alpha=1/5)
##其他常用的统计函数
flights_not_cancelled %>% group_by(dest) %>% summarise(carrier=n())
flights_not_cancelled %>% group_by(dest) %>% summarise(carriers=n_distinct(carrier))
flights_not_cancelled %>% group_by(tailnum) %>% summarise(sum(distance))
 
###exercises
##### 查看哪个航空公司延误时间最长
flights_not_cancelled %>% group_by(carrier) %>% summarise(count=n(),arr_delay_time=mean(arr_delay)) %>% arrange(desc(arr_delay_time)) %>% ggplot(mapping = aes(x=carrier,y=arr_delay_time))+geom_point(aes(size=count))

  1. 取消分组:ungroup()函数:
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 写在前面 ggplot2 是一个功能强大且灵活的R包 ,由Hadley Wickham 编写,其用于生成优雅的图...
    Boer223阅读 27,335评论 0 67
  • 刘小泽开始写于18.9.4晚,这必定是一个持续性更新的过程昨天jimmy一发朋友圈,单篇阅读量很快超过了我们的关注...
    刘小泽阅读 1,133评论 0 12
  • 今天发现了不一样的美,简简单单 熟悉的咖啡吧,别样的情调 熟悉的广场,不一样的灯光 熟悉的湖,不一样的心情 生活本...
    Mr玉民阅读 200评论 0 0
  • 其实本来就想下班后好好写东西给你,谁知道发生了被盗刷这种事。唉。 我想说,你才是我的动力。没有你,我是不可能过会计...
    苍洱皑皑白首不易阅读 292评论 0 1
  • 心中就像被人绞 心伤唯有自己晓 可怜自己是懦夫 只能借酒浇心伤
    Crazy辰尘阅读 183评论 0 0