week3note控制语句

1. switch语句

switch是多分支语句,其用法为:

switch (statement, list);

statement是一个表达式,list是列表,也可以用有名定义。根据表达式与list的关系返回一个值。如果表达式返回值属于1:length(list)中的一个,则返回list中相应位置的值,否则返回NULL

example:

a <- switch (2, 2+2, mean(1:10), rnorm(4))
[1]  5.5 


x <- "fruit";
a <- switch (x, fruit="apple", drink="coffee", vegetable="broccoli"); a 
[1]  "apple"

2. for语句

循环结构中常用的是for循环,是对一个向量或列表的逐次处理,格式为

for( name in values) 
{expression} 

2.1 ex:Hilbert矩阵构造

构造3阶Hilbert矩阵,Hilbert矩阵的分量满足 H[i,j]=1/(i+j-1)

H <- matrix(0, ncol=3, nrow=3)
for (i in 1:3 ) {
 for (j in 1:3)  {
   H[i,j] <- 1/(i+j-1) 
 }
}
H
> H
  [,1]  [,2]  [,3]
[1,] 1.0000000 0.5000000 0.3333333
[2,] 0.5000000 0.3333333 0.2500000
[3,] 0.3333333 0.2500000 0.2000000

利用outer简化:

Hilbert <- function(x,y){
    1/(x+y-1)
}

outer(1:3,1:3,Hilbert)

  [,1]  [,2]  [,3]
[1,] 1.0000000 0.5000000 0.3333333
[2,] 0.5000000 0.3333333 0.2500000
[3,] 0.3333333 0.2500000 0.2000000

2.2 ex 概率问题

假设一共有365个生日(只考虑月、日),而且各生日的概率是相等的(这里忽略了闰年的情况以及可能存在的出生日期分布的不均匀)。设一个班有n个人,当n大于365时至少两个人生日相同是必然事件。当n小于等于365时,可以计算至少有两个人生日在同一天的概率

使用a,b,c三种方法比较时间:
#方法a
a <- function(){
x = numeric(365)
n <- 1:365
for(i in n)
{ x[i]= 1
for(j in 0:(i-1)) {
x[i]= x[i] * (365-j)/365
x[i] <- 1 - x[i] }
}
}

#方法b
b <- function(){
n <- 1:365
x <- numeric(365) 
for(i in n){ 
x[i] = 1 - prod((365:(365-i+1))/365) 
} 
}

#方法c
c <- function(){
x <- 1-cumprod((365:1)/365)
}
system.time(a())
system.time(b())
system.time(c())

结果如下:

> system.time(a())
用户 系统 流逝 
0.34 0.00 0.34 
> system.time(b())
用户 系统 流逝 
   000 
> system.time(c())
用户 系统 流逝 
   000 

2.3 读取多个文件存成list

a <- list(rep(0,2))
i=1
for (fn in list("user.txt","usersorted.txt")) {
      a[[i]] <- read.table(fn)
      i=i+1
}
a[[1]]

#结果
> a[[1]]
V1  V2  V3 V4
1 Name Sex Age Height
2Alice   F  13   56.5
3Becka   F  13   65.3
4 Gail   F  14   64.3
5Karen   F  12   56.3
6Kathy   F  12   59.8
7 Mary   F  15   66.5
8Sandy   F  11   51.3
9   Sharon   F  15   62.5
10   Tammy   F  14   62.8
11  Alfred   M  14   69.0
12Duke   M  14   63.5
13   Guido   M  15   67.0
14   James   M  12   57.3
15 Jeffrey   M  13   62.5
16John   M  12   59.0
17  Philip   M  16   72.0
18  Robert   M  12   64.8
19  Thomas   M  11   57.5
20 William   M  15   66.5

2.4 对非向量集合的循环

R并不支持直接对非向量集合的循环,但可
- 使用lapply()函数
- 使用get()函数:它接受一个代表对象名字的字符串参数,返回该对象的内容

设u、v为包含两列的数值型矩阵,则

 for (m in c("u","v")) {
    z <- get(m)
    print(lm(z[,2] ~ z[,1]))
 }

3. while repeat (略)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值