R1 Lecture 04 Class Notes
来源:互联网 发布:淘宝网上客服服务时间 编辑:程序博客网 时间:2024/04/29 20:28
R1_04 Class Notes
编程基础:控制流&函数入门
by YU,Xiang
Mar 24 2015
控制流(判断和循环)
判断 if,else,ifelse
if(statement) { do something...}else { do something else...}
练习1
写一个if else语句,功能是:
当y是偶数时,打印出y的一半,当y是奇数时,打印出3y+1
y <- 17if(y%%2==0) print(y/2) else print(3*y+1)
## [1] 52
ifelse(statement,do,do else)
练习2
使用ifelse再次完成练习1,想一想输出结果为什么不同
ifelse(y%%2==0, print(y/2), print(3*y+1))
## [1] 52
## [1] 52
ifelse(y%%2==0, y/2, 3*y+1)
## [1] 52
循环 for, while, repeat
for(x in something){ do ...}
练习3
当y取1到10时,对每一个y做练习1
for(y in 1:10){ if(y%%2==0) print(y/2) else print(3*y+1)}
## [1] 4## [1] 1## [1] 10## [1] 2## [1] 16## [1] 3## [1] 22## [1] 4## [1] 28## [1] 5
while(statement){ do ...}
练习4
用while做练习3
y <- 1while(y<=10){ if(y%%2==0) print(y/2) else print(3*y+1) y <- y+1 }
## [1] 4## [1] 1## [1] 10## [1] 2## [1] 16## [1] 3## [1] 22## [1] 4## [1] 28## [1] 5
repeat{ do... if(statement) break}
练习5
用repeat做练习3
y <- 1repeat{ if(y%%2==0) print(y/2) else print(3*y+1) y <- y+1 if(y > 10) break}
## [1] 4## [1] 1## [1] 10## [1] 2## [1] 16## [1] 3## [1] 22## [1] 4## [1] 28## [1] 5
函数
什么是函数
给定一些输入值,按照某种计算方法,得到一个结果.函数可以重复使用,能大大简化程序
f1 <- function(x){ if(x%%2==0) print(x/2) else print(3*x+1)}
函数的结构
function_name <- function(input1,input2,...){ do something... return_value}
练习6
写一个函数,对于输入
f2 <- function(x){ 2*x+sin(x)-cos(x)}
练习7
生成一个
f3 <- function(n){ mat <- matrix(0,nrow=n,ncol=n) for(i in 1:n){ for(j in 1:n){ mat[i,j] <- i^j } } mat}
练习8
Fibonacci数列是如下形式的数列:
1,1,2,3,5,8,13,21,...
请写一个函数 Fib <- function(N) 来生成Fibonacci数列的前N项
Fib <- function(N){ fib <- rep(0,N) fib[1:2] <- c(1,1) for(i in 3:N){ fib[i] <- fib[i-1] + fib[i-2] } fib}# 前二十项如下Fib(20)
## [1] 1 1 2 3 5 8 13 21 34 55 89 144 233 377## [15] 610 987 1597 2584 4181 6765
第四周作业
1.写一个函数 Fib2 <- function(N) 生成N以内的Fibnacci数列
2.写一个函数 x3p1 <- function(N) 对N以内所有正整数,检验3X+1问题是否成立
0 0
- R1 Lecture 04 Class Notes
- R1 Lecture 02 Class Notes
- R1 Lecture 05 Class Notes
- R1 Lecture 06 Class Notes
- R1 Lecture 07 Class Notes
- R1 Lecture 08 Class Notes
- R1 Lecture 09 Class Notes
- R1 Lecture 10 Class Notes
- CS229 Lecture notes 1
- Lecture Notes: Macros
- Scipy Lecture Notes
- MLDS Lecture Notes
- CS229 Lecture notes
- Week 9 Lecture Notes
- MLDS Lecture Notes Ⅱ
- Lecture Notes on Static Analysis
- MIT Computer Graphics Lecture Notes
- Lecture Notes in Computer Science
- OC实现两个按钮的互斥 checkBox
- Python两个内置函数——locals 和globals (学习笔记)
- ActiveAndroid的使用
- String to Integer (atoi) —— Leetcode
- javax.servlet.jsp.JspException cannot be resolved to a type
- R1 Lecture 04 Class Notes
- 数学之路-vb.net并行计算(6)
- STL源码:红黑树
- groovy 速学 - 10 - 映射
- start up
- canvas-js贝塞尔曲代码在线生成工具
- 分享我每天的健康养生好习惯
- ubuntu 实用工具系列文章 upstart把应用封装成系统服务
- iOS WebView加载https 网址