[R] [Johns Hopkins] R Programming -- week 3

library(datasets)
head(airquality)
#按月分組
s <- split(airquality, airquality$Month)
str(s) 
summary(s)
lapply(s,function(x) colMeans(x[,c("Ozone","Solar.R","Wind")],na.rm = T))
sapply(s,function(x) colMeans(x[,c("Ozone","Solar.R","Wind")],na.rm = T))


#多函數對照
x <- rnorm(10)
f1 <- gl(2,5)
f2 <- gl(5,2)
interaction(f1,f2)
str(split(x,list(f1,f2))) #list會自動帶入interaction()
str(split(x,list(f1,f2), drop = T)) #捨去空level

#Debug
message: 可能
warning: 意料(期望)之外的事情,提醒
error: 大問題,會stop
condition: 所有都是condition,可設計觸發

invisible() 會返回但不會顯示

 

printmessage <- function(x) {
if(x>0)
print("positive")
else
print("negative")
}
x<-log(-1) #NaN warning
printmessage2(x) #Error

 

printmessage2 <- function(x) {
if(is.na(x))
print("missing")
else if(x>0)
print("positive")
else
print("negative")
}
x<-log(-1) #NaN warning
printmessage2(x) #warning NaN => Na

#錯誤處理的思維
input甚麼,如何Call function
所期待的是甚麼,Output? message? other result?
所獲得的是甚麼
差異是甚麼
是否可再現錯誤

#Debugging Tool
1.traceback : 幾個function被呼叫,在哪裡出錯 (只能給出上一次的資料)
2.debug : 函數一開始就暫停,再一行行,搭配browser
3.browser : 函數中的停止點
4.trace : 將debuggingcode插入特別位置
5.recover : 報錯的訊息

mean(xxx)
#Error
traceback()
#1:mean(xxx)

lm(y-x)
#Error
traceback()
4: stats::model.frame(formula = y - x, drop.unused.levels = TRUE)
3: eval(mf, parent.frame())
2: eval(mf, parent.frame())
1: lm(y - x)

debug(lm) #對於lm進入debug模式
lm(y-x) #開始針對lm(y-x)進行debug
#Browse[2]> #一步步檢查
debug: ret.x <- x
#Browse[2]> 
debug: ret.y <- y
#Browse[2]> 
debug: cl <- match.call()
.
.
#Browse[2]> 
Error in stats::model.frame(formula = y - x, drop.unused.levels = TRUE) : 
object 'y' not found


可藉由options(error = recover)將recover函數作為錯誤處理器 (此處為globel層級的設定)
tracback中的步驟列表功能,即為recover中的功能,不過recover可以選擇步驟查看其environment
原文地址:https://www.cnblogs.com/pyleu1028/p/10391434.html