R语言各种方法总结及实例

来源:互联网 发布:大淘营复制软件 编辑:程序博客网 时间:2024/06/17 15:38

R语言的条件控制语句

条件控制语句--

1if-else语句

2switch语句

 

If-else语句

(1):if(cond) statement_1

(2):if(cond) statement_1

       else statement_2

(3)Ifelse

 

用法实例:

> x<-3> #运行完之后值存放在y中> if(x>2) y<-2*x else y<-3*x> x[1] 3> y[1] 6> #运行完之后不仅将值存放在y中,还会将值返回> x<-1> ifelse(x>2,y<-2*x,y<-3*x)[1] 3> y[1] 3Swith()循环:实例:> #第一个参数表示运行后面第几个表达式> switch (1,2*3,sd(1:5),runif(3))[1] 6> switch (2,2*3,sd(1:5),runif(3))[1] 1.6> switch (3,2*3,sd(1:5),runif(3))[1] 0.163 0.095 0.862> feelings<-c("sad","afraid")> for (i in feelings) {+   print(+     switch (i,happy="I am glad you are happy",+             afraid="There is nothing to fear",+             sad="Cheer up",+             angry="Calm down now"+     )+     +   )+ }[1] "Cheer up"[1] "There is nothing to fear"> #for不带大括号> for (i in feelings) +   print(+     switch (i,happy="I am glad you are happy",+             afraid="There is nothing to fear",+             sad="Cheer up",+             angry="Calm down now"+     )+     +   )[1] "Cheer up"[1] "There is nothing to fear"

 

 

循环语句

1)for语句

2)while语句

3)repeat语句

 

一、for循环

二、While循环

三、Repeat循环

实例:

> #for> Fibonacci<-NULL> mode(Fibonacci)[1] "NULL"> Fibonacci[1]<-Fibonacci[2]<-1> n=16> for (i in 3:n) {+   Fibonacci[i]<-Fibonacci[i-2]+Fibonacci[i-1]+ }> #while> i<-3> while(Fibonacci[i-2]+Fibonacci[i-1]<1000){+   Fibonacci[i]<-Fibonacci[i-2]+Fibonacci[i-1]+   i<-i+1+   }> Fibonacci  [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987> i<-1> while(Fibonacci[i]+Fibonacci[i+1]<1000){+   Fibonacci[i+2]<-Fibonacci[i]+Fibonacci[i+1]+   i<-i+1+ }> Fibonacci [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987 > i<-1> repeat{+   Fibonacci[i+2]<-Fibonacci[i]+Fibonacci[i+1]+   i<-i+1+   if(Fibonacci[i]+Fibonacci[i+1]>=1000) break+ }> Fibonacci [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

 

用户自定义函数

#%A:星期几  %B:月份  %d:日期  %Y:年%m%d%Y

#cat会把参数拼接在一起

mydate<-function(type="long")

{

  switch (type,

    long=format(Sys.time(),"%A %B %d %Y"),

    short=format(Sys.time(),"%m-%d-%Y"),

    cat(type,"is not a recognized type\n")

  )

}

#调用自定义函数

mydate("long")

#因为函数madate定义的时候把"long"作为了默认的类型了,所以不带参数也可以

mydate()

mydate("short")

#带人一个非法值

mydate("media")

> #%A:星期几  %B:月份  %d:日期  %Y:年 %m月%d日%Y年

> #cat会把参数拼接在一起

> mydate<-function(type="long")

+ {

+   switch (type,

+     long=format(Sys.time(),"%A %B %d %Y"),

+     short=format(Sys.time(),"%m-%d-%Y"),

+     cat(type,"is not a recognized type\n")

+   )

+ }

> #调用自定义函数

> mydate("long")

[1] "星期三 五月 25 2016"

> #因为函数madate定义的时候把"long"作为了默认的类型了,所以不带参数也可以

> mydate()

[1] "星期三 五月 25 2016"

> mydate(short)

Error in mydate(short) : object 'short' not found

> mydate("short")

[1] "05-25-2016"

> #带人一个非法值

> mydate("media")

media is not a recognized type

 

函数优化求解

           ---------一元函数优化

           ---------多元函数优化

一元优化函数:

第一个参数是函数表达式;第二个参数是interval:参数的收索区间;lower:参数的

收索下限;upper:参数收索上线;maximum=FALSE:默认是求极小值;tol:精度的容忍度

optimaize(f=interval=,lower=,upper=,maximum=FALSE;tol=)

> #定义一个函数f(x)=ln(x)-x^2

> f<-function(x) log(x)-x^2

> #画曲线

> curve(f,xlim = c(0,2))

> #优化

> optimize(f,c(0.1,10),tol=0.0001,maximum = T)

$maximum

[1] 0.7071232

 

$objective

[1] -0.8465736

 

 

 

多元函数优化:

第一个参数par:给出取值范围;fngr=NULL:梯度默认是空;loweruppermethodcontrol=list();hessian=FALSE

Optim(par,fn)

 

什么是函数的整合(aggregate)与重塑(reshape)

整合:

多组观测--->观测计算的描述性统计量

重塑:

修改数据到结构(行和列)决定组织方式

 

Mtcars----34种车型的设计和性能特点

转置:

实现方式:t()

 

整合函数:

aggregate(x,by,FUN):x是待折叠的数据对象,by:变量名组成的列表;FUN:用来计算描述型统计量的标量的函数

按照汽车的汽缸和档位

 

reshape包:它是一套整合和重构数据集的绝妙万能工具

Library(reshape)

Md<-melt(mydata,id=(“id”,”time”))

 

重铸:

使用已经融合的数据,然后使用公式/函数进行重铸

Newdat<-cast(md,formula,FUN)

 

 

 

cars<-mtcars[1:5,1:4]

cars

t(cars)

 

options(digits = 3)

attach(mtcars)

#by中的变量一定要放在list

aggdate<-aggregate(mtcars,by=list(cyl,gear),FUN=mean,na.rm=TRUE)

aggdate

#Group.1气缸数,Group.2档位

 

install.packages("reshape")

library("reshape")

id<-rep(1:2,each=2)

id

time<-rep(1:2,2)

time

x1<-c(5,3,6,2)

x2<-c(6,5,1,4)

mydata<-data.frame(id,time,x1,x2)

mydata

#融合

md<-melt(mydata,id=(c("id","time")))

md

#重铸

#id做统计,计算出均值

cast(md,id~variable,mean)

#time做统计,计算出均值

cast(md,time~variable,mean)

##idtime做统计,计算出均值

cast(md,id~time,mean)

cast(md,id+time~variable)

cast(md,id~variable~time)

cast(md,id+variable~time)

cast(md,id~variable+time)

 

 > cars<-mtcars[1:5,1:4]> cars                   mpg cyl disp  hpMazda RX4         21.0   6  160 110Mazda RX4 Wag     21.0   6  160 110Datsun 710        22.8   4  108  93Hornet 4 Drive    21.4   6  258 110Hornet Sportabout 18.7   8  360 175> t(cars)     Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportaboutmpg         21            21       22.8           21.4              18.7cyl          6             6        4.0            6.0               8.0disp       160           160      108.0          258.0             360.0hp         110           110       93.0          110.0             175.0> options(digits = 3)> attach(mtcars) > aggdate<-aggregate(mtcars,by=list(cyl,gear),FUN=mean,na.rm=TRUE)> aggdate  Group.1 Group.2  mpg cyl disp  hp drat   wt qsec  vs   am gear carb1       4       3 21.5   4  120  97 3.70 2.46 20.0 1.0 0.00    3 1.002       6       3 19.8   6  242 108 2.92 3.34 19.8 1.0 0.00    3 1.003       8       3 15.1   8  358 194 3.12 4.10 17.1 0.0 0.00    3 3.084       4       4 26.9   4  103  76 4.11 2.38 19.6 1.0 0.75    4 1.505       6       4 19.8   6  164 116 3.91 3.09 17.7 0.5 0.50    4 4.006       4       5 28.2   4  108 102 4.10 1.83 16.8 0.5 1.00    5 2.007       6       5 19.7   6  145 175 3.62 2.77 15.5 0.0 1.00    5 6.008       8       5 15.4   8  326 300 3.88 3.37 14.6 0.0 1.00    5 6.00> install.packages("reshape")trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.2/reshape_0.8.5.zip'Content type 'application/zip' length 127545 bytes (124 KB)downloaded 124 KBpackage ‘reshape’ successfully unpacked and MD5 sums checked The downloaded binary packages are inC:\Users\Administrator\AppData\Local\Temp\RtmpOaEEC5\downloaded_packages> library("reshape")Warning message:程辑包‘reshape’是用R版本3.2.5 来建造的 > id<-rep(1:2,each=2)> id[1] 1 1 2 2> time<-rep(1:2,2)> time[1] 1 2 1 2> x1<-c(5,3,6,2)> x2<-c(6,5,1,4)> mydata<-data.frame(id,time,x1,x2)> mydata  id time x1 x21  1    1  5  62  1    2  3  53  2    1  6  14  2    2  2  4> md<-melt(mydata,id=(c("id","time")))> md  id time variable value1  1    1       x1     52  1    2       x1     33  2    1       x1     64  2    2       x1     25  1    1       x2     66  1    2       x2     57  2    1       x2     18  2    2       x2     4 > cast(md,id~variable,mean)  id x1  x21  1  4 5.52  2  4 2.5> cast(md,time~variable,mean)  time  x1  x21    1 5.5 3.52    2 2.5 4.5> cast(md,id~time,mean)  id   1 21  1 5.5 42  2 3.5 3> cast(md,id+time~variable)  id time x1 x21  1    1  5  62  1    2  3  53  2    1  6  14  2    2  2  4> cast(md,id~variable~time), , time = 1    variableid  x1 x2  1  5  6  2  6  1 , , time = 2    variableid  x1 x2  1  3  5  2  2  4> cast(md,id+variable~time)  id variable 1 21  1       x1 5 32  1       x2 6 53  2       x1 6 24  2       x2 1 4> cast(md,id~variable+time)  id x1_1 x1_2 x2_1 x2_21  1    5    3    6    52  2    6    2    1    4 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

0 0
原创粉丝点击