R中使用return(message(""))
例子:
tt = function(dat){
# 判断如果数据的列数为3列,就退出,给出提示,如果是其它列,打印数据前六行。
if(dim(dat)[2] == 3){
return(message("错误,数据是三列"))
}else{
head(dat)
}
}
t1 = data.frame(ID=1:10,y1=rnorm(10),y2=rnorm(10))
t2 = data.frame(ID=1:10,y1=rnorm(10),y2=rnorm(10),y3=rnorm(10))
tt(t1)
tt(t2)
结果:
> tt(t1)
错误,数据是三列
> tt(t2)
ID y1 y2 y3
1 1 1.025571370 0.3317820 -0.6002596
2 2 -0.284773007 1.0968390 2.1873330
3 3 -1.220717712 0.4351815 1.5326106
4 4 0.181303480 -0.3259316 -0.2357004
5 5 -0.138891362 1.1488076 -1.0264209
6 6 0.005764186 0.9935039 -0.7104066
可以看出:
- 数据为三列时,程序退出,给出提示
- 数据为其它列时,程序运行,打印前六行