R語言學習筆記(四)流程函式及自定義函式
阿新 • • 發佈:2019-01-22
if(FALSE){條件執行}
if(FALSE){if-else結構,多重判斷}
if(FALSE){對score進行等級判定}
score = 65
if(score >= 90){
print("Excellent!")
}else if(score >= 75){
print("Good!")
}else if(score >= 60){
print("Middle!")
}else{
print("Failed!")}
if(FALSE){ifelse結構,使用:
ifelse(cond, statement1, statement2)
若cond為真,則執行statement1,否則,執行statement2.
}
score=55
ifelse(score >= 60, print("Passed!"), print("Failed!"))
if(FALSE){switch()結構}
city = 'BJ'
print(switch(city,
'SH' = 'shanghai',
'BJ' = 'beijing',
'GZ' = 'guangzhou',
'SZ' = 'shenzhen'))
if(FALSE){重複和迴圈}
if(FALSE){for結構,語法為:for(var in seq) statement}
for (i in 1:10){print("Hello world!")}
if(FALSE){while結構,語法為:while(cond) statement}
if(FALSE){while結構中的break,next命令,與C語言中的break,continue命令相同}
if(FALSE){計算1+2+...+100}
sum <- 0
i <- 0
while(i<= 100){
sum <- sum+i
i = i+1
}
if(FALSE){repeat()結構,在執行第一次迴圈的時候不管條件是否滿足,均會執行一遍}
test_word <- 'Hello, welcome to the third class!'
cnt <- 2
repeat{
print(test_word)
cnt <- cnt+1
if(cnt > 6){
break
}
}
if(FALSE){使用者自定義函式,關鍵字為function,輸入、返回的引數為任意的資料型別}
myfunc <- function(a,b,c){
return(a+b+c)
}
print(myfunc(61,72,83))
if(FALSE){使用函式的一個例子}
if(FALSE){計算資料框df中的col列的總和,並以60為分界線判斷是否通過,檔名為“delete.R”}
scoreGrade <- function(df, col){
rows <- dim(df[col])[1]
totalScore <- 0
grade <- rep("0",rows)
for(i in 1:rows){
totalScore <- totalScore+df[i,col]
grade[i] <- ifelse(df[i,col] >= 60, "passed", "failed")
}
print(paste("Sum of ",col," is ",totalScore,"."))
return(cbind(df,grade))
}
使用的資料框為:
執行情況如下圖:
本次分享到此結束,歡迎大家交流及批評~~