一、switch函数介绍
switch 语句是多分支 ,使用方法:switch (statement, list) 其中statement是表达式,list是列表,可以用有名定义。
1. 如果statement是介于1到length(list)之间的整数,返回list对应位置的值;否则不返回值
2. list是有名定义时,statement 等于变量名时,返回变量名对应的值;否则不返回值
二、示例
编写一个函数,它以日期为输入参数,并能返回对应于当天的星座。每个星座的日期范围列于下表:
Constellation <- function(date){
Cdate <- as.Date(date,format='%Y-%m-%d')
if(is.na(Cdate)) print("请输入XXXX-XX-XX格式") ##参数传入规定格式
else{
Cdate <- as.POSIXlt(Cdate)
m <- Cdate$mon+1 ####取月份
d <- Cdate$mday ####取天
n <- switch(m,
Jan = ifelse(d < 20, 12 ,1),
Feb = ifelse(d < 19, 1, 2),
Mar = ifelse(d < 21, 2, 3),
Apr = ifelse(d < 20, 3, 4),
May = ifelse(d < 21, 4, 5),
Jun = ifelse(d < 21, 5, 6),
Jul = ifelse(d < 23, 6, 7),
Aug = ifelse(d < 23, 7, 8),
Sep = ifelse(d < 23, 8, 9),
Oct = ifelse(d < 22, 9, 10),
Nov = ifelse(d < 22, 10, 11),
Dec = ifelse(d < 22, 11, 12)
)
constellation <- c("水瓶座", "双鱼座","白羊座","金牛座","双子座","巨蟹座","狮子座",
"处女座","天秤座","天蝎座","射手座","摩羯座")
return(constellation[n])
}
}
注:switch函数适用于分段函数分段较多的情况,可以事先对定义域的值分段,再使用switch函数会简化代码(运行速度方面没有做过测试)
参考文献:
[1] 薛毅,陈丽萍等.统计建模与R软件[M].北京:清华大学出版社,2007:110-112.