目录
1.tidyverse包基础
1.0 下载使用tidyverse
1.1 数据清洗
1.1.1 提取数据
1.1.2 数据整理与采样
1.1.3 缺省值处理
1.1.4 重复值处理
1.1.5 异常值处理
1.2 数据预处理
1.2.1 数据标准化
1.2.2 数据编码
1.tidyverse包基础
1.0 下载使用tidyverse
tidyverse包有很多依赖,大概率在安装的时候,会报错如:
这时不要惊慌,那是因为你没有安装libcurl4-openssl-dev,openssl这些软件,在系统里安装这些软件就好了,比如在ubuntu系统,执行以下命令
apt-get install libcurl4-openssl-dev openssl
1.1 数据清洗
1.1.1 提取数据
#data为tibble数据类型
data <- read_csv( filepath, col_types=cols() )
1.1.2 数据整理与采样
根据业务需求和目标,整理出有用的数据。
选取name ,age列
select(data,name,age,sex)
filter(data,age>=15,sex=='F) head(data,n=10) tail(data,n=10) slice(data,1:10)
sample_n(data,size = 10) #无放回 sample_n(data,size= 10,replace=TRUE) #有放回 sample_n(data,size=10,weight = 1/height) #让height越小的人越容易抽样抽取到,不等概率抽样
1.1.3 缺省值处理
- 去除任意列数据中含有na的行数据(去除所有包含NA的行)
drop_na(data)
drop_na(data,age,sex)
1.1.4 重复值处理
distinct() # 去除完全相同的行,只保留一行 distinct(name,sex,weight) #去除在三列数据上完全一致的行,只保留一行
1.1.5 异常值处理
arrange(data,age,desc(height)) # age升序后,再对height降序
# 计算BMI值 data%>% mute( height_cm = round(height*2.54), weight_kg = round(weight*0.4535924), bmi = weight_kg / (height_cm / 100)^2) )
1.2 数据预处理
1.2.1数据标准化
data%>% select(height,weight)%>% scale() #默认标准化为均值为0方差为1的分布 scale(center=apply(.,2,min),scale=apply(.,2,max)-apply(.,2,min))) #放缩至0-1
1.2.2 数据编码
data['sex'] = ifelse(data['sex']=='F',0,1) # F 编码为0,M编码为1