R语言-v1-基础知识

Python012

R语言-v1-基础知识,第1张

R语言-v1-基础知识

Iretara  12-17 21:18

以例题的形式简述R语言基础知识

# 读取文件

setwd(" 文件链接的时候,用  /  ")

install.packages(" readxl ")

library(readxl)

library (tidyverse)

hw1_a<- read_excel ("hw1_a.xlsx", col_types=c("numeric", "numeric", "numeric", "numeric", "numeric") )

hw1_b<- read_excel ("hw1_b.xlsx")

#读取csv

library(readr)

hw1_a<- read_csv ("/")

View(hw1_a)

# 描述型函数

hw1_a + hw1_b 表

#描述最小值,最大值,中值,均值,标准差

Str (hw1_a) #查看数据并指出各个 变量的形式

summary (hw1_a) #指出各个变量的形式, 最小值,最大值,中值,均值

library(psych)

describe (hw1_a) #比summary更简便的方法, 可以直接读取标准差等;但是,使用describe不可读取 NA值, 可以尝试使用 Hmisc包中 describe

描述型函数-R

# 连接

hw1_a %>% inner_join (hw1_b, by ="ID")

hw1_a %>% left_join (hw1_b, by ="ID")

hw1_a %>% right_join (hw1_b, by ="ID")

hw1_a %>% full_join (hw1_b, by ="ID")

inner_join<- inner_join (hw1_a,hw1_b, by =“ID”) #报告合并后的 总行数 ,178行

full_join<- full_join (hw1_a,hw1_b, by ="ID")

( nrow (full_join)) #报告合并后的 总行数 ,200行

>  length (full_join$ID)

#找出各个列的 缺失值

i<-NA

a<-NA

for(i in 1:length(full_join[1,])){ a[i]<- sum(is.na( full_join[,i] ) ) }

paste("缺失值是",a)

#缺失值总数

sum(is.na(full_join))

#删除缺失值 na.omit()

full_join1=filter(full_join,!is.na(full_join[2]))

full_join1=filter(full_join1,!is.na(full_join1[3]))

full_join1=filter(full_join1,!is.na(full_join1[4]))

full_join1=filter(full_join1,!is.na(full_join1[5]))

full_join1=filter(full_join1,!is.na(full_join1[6]))

full_join1=filter(full_join1,!is.na(full_join1[7]))

full_join1=filter(full_join1,!is.na(full_join1[8]))

sum(is.na(full_join1))

找出Income中的 极端值 并滤掉对应行的数据

quantile (hw1_a$Income,c(0.025,0.975))

hw1_a2= filter (hw1_a,Income>14168.81 &Income<173030.92)

#使用dplyr进行数据转换

arrange()

>arrange (hw1_a,Income) #默认升序

>arrange(hw1_a, desc (Income)) #desc降序,NA排序一般最后

select()

>select (hw1_a, - (Years_at_Address:Income)) #不要变量

>rename (hw1_a, In_come=Income) #改名

>select(hw1_a,Income, exerything ()) #把Income放在前面

拓例题1:

library(nycflights13)

view(flights)

#counts

(1)

not_cancelled <- flights %>%

filter(! is.na(dep_delay), !is.na(arr_delay))

(2)

not_cancelled %>%

group_by (year,month,day) %>%

summarize (mean=mean(dep_delay))

(3)

delays <- not_cancelled %>%

group_by (tailnum) %>%

summarize (delay=mean(arr_delay))

ggplot (data=delays,mapping=aes(x= delay))+

geom_freqpoly (binwidth=10) #freqpoly

(4)

delays <- not_cancelled %>%

group_by(tailnum) %>%

summarize(delay=mean(arr_delay,na.rm=TRUE), n=n() ) #tailnum的次数

ggplot(data=delays,mapping=aes(x= n, y=delay))+

geom_point(alpha=1/10)

拓例题2:

#请按照价格的均值,产生新的变量price_new, 低于均值为“低价格”,高于均值为“高价格”。 同样对市场份额也是,产生变量marketshare_new, 数值为“低市场份额”和“高市场份额”

price=data1$price

pricebar=mean(price)

price_new= ifelse (price>pricebar,“高价格”,”低价格”)

marketshare=data1$marketshare

marketsharebar=mean(marketshare)

marketshare_new=ifelse(marketshare>marketsharebar ,“高市场份额”,”低市场份额”)

data1= mutate (data1,price_new,marketshare_new)

#可视化

#将Income 对数化

lninc<- log (hw1_a$Income)

#画出直方图和 density curve密度曲线

hist (lninc,prob=T)

lines ( density (lninc),col="blue")

# 添加额外变量 的办法,在 aes()中添加 样式 (color、size、alpha、shape)

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income, alpha= Is_Default))

# 按照Is_Default 增加一个维度,使用明暗程度作为区分方式

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income,

alpha=factor( Is_Default ) ))

#使用形状作为另外一种区分方式

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income,

shape=factor( Is_Default)))

可视化-R

拓展:

#将 flight1 表和 weather1 表根据共同变量进行内连接,随机抽取 100000 行数据, 将生产的结果保存为 flight_weather。 (提示:sample_n()函数,不用重复抽取)

flight_weather <- inner_join(flight1, weather1) %>% sample_n(100000)

# 从 flight_weather表中对三个出发机场按照平均出发延误时间排降序,并将结果保留在 longest_delay表中。把结果展示出来

longest_delay<- flight_weather %>%

group_by(origin) %>%

summarize(delay=mean(dep_delay, na.rm=TRUE )) %>%

arrange(desc(delay))

#根据不同出发地(origin)在平行的 3 个图中画出风速 wind_speed(x 轴)和出发 延误时间 dep_delay(y 轴)的散点图。

ggplot(data= flight_weather) +

geom_point(mapping=aes(x=wind_speed,y=dep_delay))+

facet_grid(.~origin, nrow = 3 ) # 按照class分类,分成3行

#根据 flight_weather 表,画出每个月航班数的直方分布图,x 轴为月份,y 轴是每个 月份航班数所占的比例。

ggplot(data=flight_weather)+

geom_bar(mapping=aes(x=month, y=..prop .., group=1))

#根据 flight_weather 表,画出每个月航班距离的 boxplot 图,x 轴为月份,y 轴为 航行距离, 根据的航行距离的中位数从低到高对 x 轴的月份进行重新排序

ggplot(data=flight_weather)+

geom_boxplot(mapping=aes(x= reorder (month,distance,FUN=median),y=distance))

线性回归

# 以Income作为因变量,Years at Employer作为自变量,进行 OLS回归

m1<- lm (Income ~ Years_at_Employer,data=hw1_a)

#通过***判断显著性

summary (m1)

#画出拟合直线

ggplot(data= hw1_a)+

geom_point(aes(x=Income,y=Years_at_Employer))+

geom_abline(data= m1,col= "blue")

#证明拟合直线是最优的

b0=runif(20000,-5,5)

b1=runif(20000,-5,5)

d<-NA

sum<-NA

n<-1

while(n<=20000){

for(i in 1:24){

d[i]<-(hw1_a $ Income[i]-b0[n]-b1[n]*hw2$ Years_at_Employer[i])^2}

sum[n]<-sum(d)

n<-n+1

}

resi=m1$residuals

resi2=sum(resi^2)

check=sum(as.numeric(sum<resi2))

check

R语言常用函数整理本篇是基础篇,即R语言自带的函数。

vector:向量

numeric:数值型向量

logical:逻辑型向量

character;字符型向量

list:列表

data.frame:数据框

c:连接为向量或列表

length:求长度

subset:求子集

seq,from:to,sequence:等差序列

rep:重复

NA:缺失值

NULL:空对象

sort,order,unique,rev:排序

unlist:展平列表

attr,attributes:对象属性

mode,class,typeof:对象存储模式与类型

names:对象的名字属性

字符型向量 nchar:字符数

substr:取子串 format,formatC:把对象用格式转换为字符串

paste()、paste0()不仅可以连接多个字符串,还可以将对象自动转换为字符串再相连,另外还能处理向量。

strsplit:连接或拆分

charmatch,pmatch:字符串匹配

grep,sub,gsub:模式匹配与替换

complex,Re,Im,Mod,Arg,Conj:复数函数

factor:因子 codes:因子的编码 levels:因子的各水平的名字 nlevels:因子的水平个数 cut:把数值型对象分区间转换为因子

table:交叉频数表 split:按因子分组 aggregate:计算各数据子集的概括统计量 tapply:对“不规则”数组应用函数

dev.new() 新建画板

plot()绘制点线图,条形图,散点图.

barplot( ) 绘制条形图

dotchart( ) 绘制点图

pie( )绘制饼图.

pair( )绘制散点图阵

boxplot( )绘制箱线图

hist( )绘制直方图

scatterplot3D( )绘制3D散点图.

par()可以添加很多参数来修改图形

title( ) 添加标题

axis( ) 调整刻度

rug( ) 添加轴密度

grid( ) 添加网格线

abline( ) 添加直线

lines( ) 添加曲线

text( ) 添加标签

legend() 添加图例

+, -, *, /, ^, %%, %/%:四则运算 ceiling,floor,round,signif

1、round() #四舍五入

例:x <- c(3.1416, 15.377, 269.7)

round(x, 0) #保留整数位

round(x, 2) #保留两位小数

round(x, -1) #保留到十位

2、signif() #取有效数字(跟学过的有效数字不是一个意思)

例:略

3、trunc() #取整

floor() #向下取整

ceiling() #向上取整

例:xx <- c(3.60, 12.47, -3.60, -12.47)

trunc(xx)

floor(xx)

ceiling(xx)

max,min,pmax,pmin:最大最小值

range:最大值和最小值 sum,prod:向量元素和,积 cumsum,cumprod,cummax,cummin:累加、累乘 sort:排序 approx和approx fun:插值 diff:差分 sign:符号函数

abs,sqrt:绝对值,平方根

log, exp, log10, log2:对数与指数函数

sin,cos,tan,asin,acos,atan,atan2:三角函数

sinh,cosh,tanh,asinh,acosh,atanh:双曲函数

beta,lbeta,gamma,lgamma,digamma,trigamma,tetragamma,pentagamma,choose ,lchoose:与贝塔函数、伽玛函数、组合数有关的特殊函数

fft,mvfft,convolve:富利叶变换及卷积

polyroot:多项式求根

poly:正交多项式

spline,splinefun:样条差值

besselI,besselK,besselJ,besselY,gammaCody:Bessel函数

deriv:简单表达式的符号微分或算法微分

array:建立数组

matrix:生成矩阵

data.matrix:把数据框转换为数值型矩阵

lower.tri:矩阵的下三角部分

mat.or.vec:生成矩阵或向量

t:矩阵转置

cbind:把列合并为矩阵

rbind:把行合并为矩阵

diag:矩阵对角元素向量或生成对角矩阵

aperm:数组转置

nrow, ncol:计算数组的行数和列数

dim:对象的维向量

dimnames:对象的维名

rownames,colnames:行名或列名

%*%:矩阵乘法

crossprod:矩阵交叉乘积(内积)

outer:数组外积

kronecker:数组的Kronecker积

apply:对数组的某些维应用函数

tapply:对“不规则”数组应用函数

sweep:计算数组的概括统计量

aggregate:计算数据子集的概括统计量

scale:矩阵标准化

matplot:对矩阵各列绘图

cor:相关阵或协差阵

Contrast:对照矩阵

row:矩阵的行下标集

col:求列下标集

solve:解线性方程组或求逆

eigen:矩阵的特征值分解

svd:矩阵的奇异值分解

backsolve:解上三角或下三角方程组

chol:Choleski分解

qr:矩阵的QR分解

chol2inv:由Choleski分解求逆

><,>,<=,>=,==,!=:比较运算符 !,&,&&,|,||,xor():

逻辑运算符 logical:

生成逻辑向量 all,

any:逻辑向量都为真或存在真

ifelse():二者择一 match,

%in%:查找

unique:找出互不相同的元素

which:找到真值下标集合

duplicated:找到重复元素

optimize,uniroot,polyroot:一维优化与求根

if,else,

ifelse,

switch:

分支 for,while,repeat,break,next:

循环 apply,lapply,sapply,tapply,sweep:替代循环的函数。

function:函数定义

source:调用文件 ’

call:函数调用 .

C,.Fortran:调用C或者Fortran子程序的动态链接库。

Recall:递归调用

browser,debug,trace,traceback:程序调试

options:指定系统参数

missing:判断虚参是否有对应实参

nargs:参数个数 stop:终止函数执行

on.exit:指定退出时执行 eval,expression:表达式计算

system.time:表达式计算计时

invisible:使变量不显示

menu:选择菜单(字符列表菜单)

其它与函数有关的还有:

delay,

delete.response,

deparse,

do.call,

dput,

environment ,

formals,

format.info,

interactive,

is.finite,

is.function,

is.language,

is.recursive ,

match.arg,

match.call,

match.fun,

model.extract,

name,

parse 函数能将字符串转换为表达式expression

deparse 将表达式expression转换为字符串

eval 函数能对表达式求解

substitute,

sys.parent ,

warning,

machine

cat,print:显示对象

sink:输出转向到指定文件

dump,save,dput,write:输出对象

scan,read.table,readlines, load,dget:读入

ls,objects:显示对象列表

rm, remove:删除对象

q,quit:退出系统

.First,.Last:初始运行函数与退出运行函数。

options:系统选项

?,help,help.start,apropos:帮助功能

data:列出数据集

head()查看数据的头几行

tail()查看数据的最后几行

每一种分布有四个函数:

d―density(密度函数),p―分布函数,q―分位数函数,r―随机数函数。

比如,正态分布的这四个函数为dnorm,pnorm,qnorm,rnorm。下面我们列出各分布后缀,前面加前缀d、p、q或r就构成函数名:

norm:正态,

t:t分布,

f:F分布,

chisq:卡方(包括非中心)

unif:均匀,

exp:指数,

weibull:威布尔,

gamma:伽玛,

beta:贝塔

lnorm:对数正态,

logis:逻辑分布,

cauchy:柯西,

binom:二项分布,

geom:几何分布,

hyper:超几何,

nbinom:负二项,

pois:泊松

signrank:符号秩,

wilcox:秩和,

tukey:学生化极差

sum, mean, var, sd, min, max, range, median, IQR(四分位间距)等为统计量,

sort,order,rank与排序有关,

其它还有ave,fivenum,mad,quantile,stem等。

R中已实现的有chisq.test,prop.test,t.test。

cor,cov.wt,var:协方差阵及相关阵计算

biplot,biplot.princomp:多元数据biplot图

cancor:典则相关

princomp:主成分分析

hclust:谱系聚类

kmeans:k-均值聚类

cmdscale:经典多维标度

其它有dist,mahalanobis,cov.rob。

ts:时间序列对象

diff:计算差分

time:时间序列的采样时间

window:时间窗

lm,glm,aov:线性模型、广义线性模型、方差分析

quo()等价于quote()

enquo()等价于substitute()

acf(int[,2], lag.max = 15,type = "correlation", plot = TRUE,main='int monthly

acf(int.l[,2], lag.max = 15,type = "correlation", plot = TRUE,main='int monthly

log return')

Box.test(int[,2], lag = 5, type = "Ljung-Box")

Box.test(int[,2], lag = 10, type = "Ljung-Box")

Box.test(int.l[,2], lag = 5, type = "Ljung-Box")

Box.test(int.l[,2], lag = 10, type = "Ljung-Box")

运行结果有以下错误,怎么办?

>int <- read.table("d-intc7208.txt", head=T)

错误于file(file, "rt") : 无法打开链结

此外: 警告信息:

In file(file, "rt") :

无法打开文件'd-intc7208.txt': No such file or directory

+ acf(int.l[,2], lag.max = 15,type = "correlation", plot = TRUE,main='int monthly

错误: 意外的符号 in:

"

acf(int.l[,2], lag.max = 15,type = "correlation", plot = TRUE,main='int"

>log return')

错误: 意外的符号 in "log return"