R语言程序设计week2

2.1控制结构

如下图


如if 

if(x>3){                                       这种写法较常见,有特色的则是这种           y<-  if(x>-3) {

y<-10  10

}else{ }else{

y<-0 0

} }




seq_along(x) 输入是一个向量,输出为一个同等长度的向量。在第三个例子中letter其实是一个索引,用letter,h,a ,b ,如果喜欢的话shit也行,这说明索引可以不只用数值

下面是一个内嵌式的for 循环





那个coin相当于抛硬币,是1的话z就加1,否则减1,直到z不满足while中的条件为止



好吧,这一个在很多结果优化中有用到,repeat在使用的时候最后加个循环次数的限制之类的。

所以return要注意,它等于中断循环外加返回值


2.2函数

这里主要讲了就一个参数匹配的问题





在这个图中如果 f <-function(a,b){b^2},那么结果则是Error in f(2) : argument "b" is missing, with no default,其实本质是还是位置匹配啊




有意思的是lazy evaluation的问题



那么。。。的用途还有一种如

输入args(paste) 

结果是  function (..., sep = " ", collapse = NULL) 

....当参数传给函数的时候而未知的时候,也要用....,如此处的paste的第一个参数是未知的


2.3 scoping rules



如上图base一般会在表的最后,而最前则是environ。search()其实就是搜索的列表罢了

dynamic scoping 动态作用域     scoping rule作用域规则   lexical scoping词法作用域  static scoping静态作用域


在上图中可瞄到,x,y 是形参。而z又非局部变量。







Lexical vs. Dynamic Scoping

When a function is defined in the global environment and is subsequently called from the global environment, then the defining environment and the calling environment are the same. This can sometimes give the appearance of dynamic scoping.

> g <- function(x) { 
+ a <- 3
+ x+a+y 
+ }
> g(2)
Error in g(2) : object "y" not found
> y <- 3
> g(2)
[1] 8





Application: Optimization

Why is any of this information useful?

  • Optimization routines in R like optimnlm, and optimize require you to pass a function whose argument is a vector of parameters (e.g. a log-likelihood)
  • However, an object function might depend on a host of other things besides its parameters (like data)
  • When writing software which does optimization, it may be desirable to allow the user to hold certain parameters fixed

Maximizing a Normal Likelihood

Write a “constructor” function

make.NegLogLik <- function(data, fixed=c(FALSE,FALSE)) {
        params <- fixed
        function(p) {
                params[!fixed] <- p
                mu <- params[1]
                sigma <- params[2]
                a <- -0.5*length(data)*log(2*pi*sigma^2)
                b <- -0.5*sum((data-mu)^2) / (sigma^2)
                -(a + b)
        } 
}

Note: Optimization functions in R minimize functions, so you need to use the negative log-likelihood.


Maximizing a Normal Likelihood

> set.seed(1); normals <- rnorm(100, 1, 2)
> nLL <- make.NegLogLik(normals)
> nLL
function(p) {
                params[!fixed] <- p
                mu <- params[1]
                sigma <- params[2]
                a <- -0.5*length(data)*log(2*pi*sigma^2)
                b <- -0.5*sum((data-mu)^2) / (sigma^2)
                -(a + b)
        }
<environment: 0x165b1a4>
> ls(environment(nLL))
[1] "data"   "fixed"  "params"

Estimating Parameters

> optim(c(mu = 0, sigma = 1), nLL)$par
      mu    sigma
1.218239 1.787343

Fixing σ = 2

> nLL <- make.NegLogLik(normals, c(FALSE, 2))
> optimize(nLL, c(-1, 3))$minimum
[1] 1.217775

Fixing μ = 1

> nLL <- make.NegLogLik(normals, c(1, FALSE))
> optimize(nLL, c(1e-6, 10))$minimum
[1] 1.800596

Plotting the Likelihood

nLL <- make.NegLogLik(normals, c(1, FALSE))
x <- seq(1.7, 1.9, len = 100)
y <- sapply(x, nLL)
plot(x, exp(-(y - min(y))), type = "l")

nLL <- make.NegLogLik(normals, c(FALSE, 2))
x <- seq(0.5, 1.5, len = 100)
y <- sapply(x, nLL)
plot(x, exp(-(y - min(y))), type = "l")


Lexical Scoping Summary

  • Objective functions can be “built” which contain all of the necessary data for evaluating the function
  • No need to carry around long argument lists — useful for interactive and exploratory work.
  • Code can be simplified and cleand up
  • Reference: Robert Gentleman and Ross Ihaka (2000). “Lexical Scope and Statistical Computing,” JCGS, 9, 491–508.

好吧,接下来是R的向量化运算的一些小点

如x<-c(1.3.5)

x==3 其实如同c(1,3,5)==c(3,3,3)

另一矩阵运算的话,如x<-matrix(1:4,2,2) y<-matrix(rep(10,4),2,2)

x*y就是矩阵内每个元素的乘积,x%*%y才是真正的矩阵运算。

2.4时间与日期

R有时间与日期的特殊的呈现方式

dates by  Date class

Times by  POSIXct or POSIXlt class

dates are stored internally(内在的)as the number of days since 1970-01-01

times are stored internally as the number of seconds since 1970-01-01

在使用的时候可用as.Date将字符转为日期

如:x
[1] "1970-01-01"
> class(x)
[1] "Date"
> unclass(x)
[1] 0
> unclass(as.Date("1970-01-01"))
[1] 0
> unclass
(as.Date("1970-01-03"))
[1] 2

unclass之后就是天数了哟,哈哈

另一个关于unclass的例子

> class(m)
[1] "data.frame"
> unclass(m)
$myFamilyAges
[1] 43 42 12  8  5


$myFamilyGenders
[1] Male   Female Female Male   Female
Levels: Female Male


attr(,"row.names")
[1] 1 2 3 4 5


示例如下:

x<-Sys.time()
> x
[1] "2014-07-10 16:03:18 CST"
> p <-as.POSIXlt(x)
> p
[1] "2014-07-10 16:03:18 CST"

names(unclass(p))
 [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"  
 [7] "wday"   "yday"   "isdst"  "zone"   "gmtoff"
> p$sec
[1] 18.1878

 unclass(x)
[1] 1404979398

果真是列表形式啊哈,与另一种POSIXct的区别






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值