版权声明:All rights reserved by LK12, reprint please explain the source https://blog.csdn.net/qq_40527086/article/details/83003181
R语言学习笔记四 数据预处理
以一个真实的自带小数据集iris为例,对其进行数据预处理并介绍相关函数。
data = iris #将data数据集赋给data
summary(data) #查看数据描述
head(data) #查看前五行
tail(data) #查看尾五行
View(data) #以视图模式查看数据集
sum(data[[1]]>5,na.rm = T) #查看某属性筛选条件下的值
可以发现数据集长成下面这种样子,著名的iris花数据集。
1.缺失值处理
假设我们让其中的数值数据中的9个变为缺失值
data = iris
m = sample(1:nrow(data),3,replace = F) #随机采样3个行下标
m
>[1] 118 67 39
n = sample(1:(ncol(data)-1),3,replace = F) #随机采样3个列下标
n
>[1] 2 3 4
data[m,n] = NA #3*3=9个采样值置为NA
现在,我们的数据集中就存在了9个缺失值。
is.na(data)
table(is.na(data))
>FALSE TRUE
741 9
sum(is.na(data))
>[1] 9
aVector = data[[n[1]]]
aVector
>[1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 3.4 3.0 3.0 4.0 4.4 3.9 3.5 3.8 3.8 3.4 3.7 3.6 3.3 3.4
[26] 3.0 3.4 3.5 3.4 3.2 3.1 3.4 4.1 4.2 3.1 3.2 3.5 3.6 NA 3.4 3.5 2.3 3.2 3.5 3.8 3.0 3.8 3.2 3.7 3.3
[51] 3.2 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 2.0 3.0 2.2 2.9 2.9 3.1 NA 2.7 2.2 2.5 3.2 2.8 2.5 2.8 2.9
[76] 3.0 2.8 3.0 2.9 2.6 2.4 2.4 2.7 2.7 3.0 3.4 3.1 2.3 3.0 2.5 2.6 3.0 2.6 2.3 2.7 3.0 2.9 2.9 2.5 2.8
[101] 3.3 2.7 3.0 2.9 3.0 3.0 2.5 2.9 2.5 3.6 3.2 2.7 3.0 2.5 2.8 3.2 3.0 NA 2.6 2.2 3.2 2.8 2.8 2.7 3.3
[126] 3.2 2.8 3.0 2.8 3.0 2.8 3.8 2.8 2.8 2.6 3.0 3.4 3.1 3.0 3.1 3.1 3.1 2.7 3.2 3.3 3.0 2.5 3.0 3.4 3.0
meanaVector = mean(aVector,na.rm = T)
meanaVector
>[1] 3.053061
missingObj = is.na(aVector)
aVector = replace(aVector,missingObj,meanaVector)#aVector中缺失值由平均值替代了
aVector[!is.na(aVector)] #过滤掉缺失值
2.处理字符的函数
2.1 计算字符串中的字符个数(nchar()函数,包含符号计数)
fruits = 'apples,oranges,pears'
nchar(fruits)
>[1]20
2.2 提取字符串中的字串(substring()函数)
fruits = 'apples,oranges,pears'
substring(fruits,1,6)
>[1] "apples"
substring(fruits,c(1,8,16),c(6,14,20))
>[1] "apples" "oranges" "pears"
2.3 对应连接粘贴函数(paste())
有时候,我们要在不同的图形上赋予不同的组合标题,可以用到这个函数将字符串和一些数字对应组合即可。
fruits = 'apples,oranges,pears'
nums = c(1,2,3)
paste(nums,fruits)
>[1] "1 apples,oranges,pears" "2 apples,oranges,pears" "3 apples,oranges,pears"
3.字符串查找和替换(正则表达式)
3.1 字符串查找(grep())
colorstrings = c('green','red','orange','blue','yellow','lightblue','navyblue','indianred')
grep('red',colorstrings,value = T) #第一个参数为查找项,第二个参数为查找向量
>[1] "red" "indianred" #返回真实值
grep('red',colorstrings,value = F) #第一个参数为查找项,第二个参数为查找向量
>[1] 2 8 #返回索引下标
grep('^red',colorstrings,value = T) #^指定起点
>[1] "red"
grep('r+',colorstrings,value = T)
>[1] "green" "red" "orange" "indianred"
grep('red$',colorstrings,value = T) #$指定终点
>[1] "red" "indianred"
grep('e{2}',colorstrings,value = T) #查找出现两次e的字符
>[1] "green"
3.2 字符串替换(gsub())
gsub()函数用于把查找项替换为指定的值,只需要多增加一个参数表示要替换的内容就可以了。
colorstrings = c('green','red','orange','blue','yellow','lightblue','navyblue','indianred')
gsub('red','brown',colorStrings)
>[1] "green" "brown" "orange" "blue" "yellow" "lightblue" "navyblue"
[8] "indianbrown" #red被成功替换为browm