R语言实战 - 高级数据管理(3)
4. 控制流
- 语句(statement)是一条单独的R语句或一组复合语句(包含在花括号{}中的一组R语句,使用分号分隔);
- 条件(cond)是一条最终被解析为真(TRUE)或假(FALSE)的表达式;
- 表达式(expr)是一条数值或字符串的求值语句;
- 序列(seq)是一个数值或字符串序列
4.1 重复和循环
> for (var in seq) statement
>
> for (i in 1:10) print("Hello")
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
>
> while (cond) statement
>
> i <- 10
> while (i > 0) {print("Hello"); i <- i - 1}
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
>
4.2 条件执行
> if (cond) statement
> if (cond) statement1 else statement2
>
> if (is.character(grade)) grade <- as.factor(grade)
> if (!is.factor(grade)) grade <- as.factor(grade) else print("Grade already is a factor")
>
>
> ifelse(cond, sttement1, statement2)
>
> ifelse(score > 0.5, print("Passed"), print("Failed"))
> outcome <- ifelse(score>0.5, "Passed", "Failed")
>
> switch(expr, ...)
>
> 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"
>
5. 用户自编函数
> myfunction <- function(arg1, arg2, ...){
+ statements
+ return(object)
+ }
>
> # 选择性地给出参数统计量(均值和标准差)
> # 和非参数统计量(中位数和绝对中位数)
> mystets <- function(x, parametric=TRUE, print=FALSE){
+ if (parametric) {
+ center <- mean(x); spread <- sd(x)
+ } else {
+ center <- median(x); spread <- mad(x)
+ }
+ if (print & parametric) {
+ cat ("Mean=", center, "\n", "SD=", spread, "\n")
+ } else if (print & !parametric) {
+ cat("Median=", center, "\n", "MAD=", spread, "\n")
+ }
+ result <- list(center=center, spread=spread)
+ return(result)
+ }
>
> set.seed(1234)
> x <- rnorm(500)
>
> y <- mystets(x)
>
> y <- mystets(x, parametric=FALSE, print=TRUE)
Median= -0.021
MAD= 1
>
> 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("log")
log is not a recognized type
> mydate("long")
[1] "Saturday September 16 2017"
> mydate("short")
[1] "09-16-17"
> mydate()
[1] "Saturday September 16 2017"
>
posted on 2017-09-15 13:07 你的踏板车要滑向哪里 阅读(174) 评论(0) 收藏 举报
浙公网安备 33010602011771号