探索性数据分析EDA-2

1、tidyverse的summarise可以用的函数:

Center: mean()median()

Spread: sd()IQR()mad()

Range: min()max()quantile()

Position: first()last()nth(),

Count: n()n_distinct()    #n=n()括号内不填参数

Logical: any()all()


2、异常值的处理:缺失值代替

diamonds1 <- diamonds %>%

  filter(between(y,3,20))#由于y的异常值从而删除了一整行数据,不推荐

diamonds2 <- diamonds %>%

  mutate(y=ifelse(y<3|y>20,NA,y))#用NA替换异常值,就可以保留整行的其他数据,推荐

nrow(diamonds2)

nrow(diamonds1)


3、有NA时,直接画图会有warnning,加上na.rm=TRUE

ggplot(data = diamonds2, mapping = aes(x = x, y = y)) +

  geom_point(na.rm=TRUE)


4、NA有意义时,比较NA与非NA值

比如,dep_time是NA代表航班取消,比较未取消的航班于取消的航班

library(nycflights13)

flights1 <- flights %>%

  mutate(cancelled=is.na(dep_time),

        dep_hour=sched_dep_time%/%100,

        dep_min=sched_dep_time%%100,

        new_dep_time=dep_hour+dep_min/60)

ggplot(data=flights1)+

  geom_freqpoly(mapping=aes(new_dep_time,colour=cancelled),binwidth=0.25)




5、如果有NA,在计算时就会返回NA

> sum(flights$dep_time,na.rm=TRUE)

[1] 443210949

> sum(flights$dep_time)

[1] NA


6、Covariation

查看不同类型钻石的价格分布,如果是freqpoly,不好比较,可以加上y=..density..,曲线下面积的总和为1

diamonds %>%

  ggplot()+

  geom_freqpoly(mapping=aes(price,color=cut),binwidth=500)

diamonds %>%

  ggplot()+

  geom_freqpoly(mapping=aes(x=price,y=..density..,color=cut),binwidth=500)


7、分类变量的连续变量分布的更好建议:箱线图+reorder()

ggplot(data=diamonds,mapping=aes(x=cut,y=price))+

  geom_boxplot()

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +

  geom_boxplot()

ggplot(data = mpg, mapping = aes(x =reorder(class,hwy,FUN=median),y=hwy)) +

  geom_boxplot()

8、#两个分类变量

1)ggplot(data=diamonds,mapping=aes(x=cut,y=color))+

  geom_count()

2)count(diamonds,color,cut)

3)diamonds %>%

  count(color, cut) %>% 

  ggplot(mapping = aes(x = color, y = cut)) +

  geom_tile(mapping = aes(fill = n))



9、两个连续变量

1)ggplot(data =diamonds)+ geom_point(mapping =aes(x =carat,y =price),alpha =1/ 100)

散点图,加透明度,数量越少,图越模糊

2)矩形图

ggplot(data=diamonds)+

  geom_bin2d(mapping=aes(x=carat,y=price))

3)使用箱线图,将其中一个连续变量用group设为分类变量的形式

ggplot(data=diamonds,mapping=aes(x=carat,y=price))+

  geom_boxplot(mapping=aes(group=cut_width(carat,0.2)))+

  coord_cartesian(xlim=c(0,4)) #笛卡尔坐标系,可以设置横纵坐标

可以设置varwidth=TRUE,使箱子的宽度与数量成正比

cut_width也可以换为cut_number

但是,箱线图只适合连续变量范围比较窄,比较集中的情况下。





最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。