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
可以看出:
- 數據爲三列時,程序退出,給出提示
- 數據爲其它列時,程序運行,打印前六行