setwd("d:/r/r-data/")
data=read.table("salary.txt",header=T)
attach(data)
mean(Salary) #工资的平均值
length(Salary) #数据个数
cumsum(Salary) #累加
salary1=cut(Salary,3) #将数据分为三组
table(salary1)
salary1=cut(Salary,3,labels=c("low","medium","high")) #给每个组设置标签
table(salary1)
breakpoints=c(0,30,40,50,60,70)
salary2=cut(Salary,breaks=breakpoints) #按区间进行分组
table(salary2)
pic=function(x){ #写一个存储过程
par(mfrow=c(2,2)) #绘图区域分割为四部分
hist(x) #直方图
dotchart(x) #点图
boxplot(x) #箱线图
qqnorm(x);qqline(x)#正态概率图
par(mfrow=c(1,1)) #恢复单图区域
}
pic(Salary) #调用编写好的函数pic()
data=read.table("d:/r/r-data/salary.txt",header=T,stringsAsFactors =F)
names(data)=c("CITY","WORK","PRICE","SALARY")
names(data) #用names函数来修改标签名
data2=data[1,3]
data3=data[-1,-3] #删除第一行第三列
attach(data)
The following object is masked from data (position 3):
CITY,PRICE,SALARY,WORK
data$SALARY=replace(SALARY,SALARY>65,NA) #将工资大于65的值改为NA
is.na(SALARY) #查找缺失值
sum(is.na(SALARY))
complete.cases(data$SALARY) #查找缺失值
data$PRICE=replace(PRICE,PRICE>80,NA)
install.packages("mice")
library(mice) #通过Mice包中的md.pattern()函数来显示缺失值模式
md.pattern(data)
install.packages("VIM")
library(VIM)
aggr(data) #通过VIM包的aggr函数来绘制数据缺失模式图
data1=data[complete.cases(data$SALARY),]
dim(data1)
data2=data[!is.na(SALARY),] #!就是非
dim(data2)
#删除缺失样本
data[is.na(data)]=mean(SALARY[!is.na(SALARY)])
#mean函数对非NA值的SALARY数据求平均值
a=c("HONGKONG",1910,75.0,41.8)
data4=rbind(data,a) #rbind按行将数据连接起来 #cbind按列将数据连接起来
data4[14:16, ]
weight=c(150,135,210,140) #数据型向量
height=c(65,61,70,65)
gender=c("F","F","M","F") #字符型向量
stu=data.frame(weight,height,gender)
row.names(stu)=c("Alice","Bob","Cal","David")
#通过data.frame函数构造数据框
index=list("City"=data$City,"Index"=1:15)
index$City
data.index=merge(data,index,by="City")
#使用merge函数将index和data合并
data[data$Salary>65,] #提取工资大于65的
data[c(2,4),] #读取第二行和第四行
data[data$Price==65.6,] #价格等于65.6的,注意要用双==
order.salary=order(stu$weight) #进行排序
order.salary
rank(data$Salary) #根据向量的秩进行排序
t(data) #进行转置
x=data.frame(A=1:4,B=seq(1.2,1.5,0.1),C=rep(1,4))
x
x1=stack(x)
x1 #把一个数据框转换成两列
unstack(x1,from=values~ind)
#还原回去
library(reshape2)
melt(x) #使用reshape2包中的melt函数将数据框转化为两列
data(airquality)
str(airquality) #显示对象的内部结构,功能类似于summary()
longdata=melt(airquality,id.vars=c("Ozone","Month","Day"),measure.vars=2:4)
str(longdata)