R语言学习笔记(四)流程函数及自定义函数

来源:互联网 发布:西安交通大学宿舍网络 编辑:程序博客网 时间:2024/06/15 10:06
if(FALSE){条件执行}if(FALSE){if-else结构,多重判断}if(FALSE){对score进行等级判定}score = 65if(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=55ifelse(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 <- 0i <- 0while(i<= 100){  sum <- sum+i  i = i+1}if(FALSE){repeat()结构,在执行第一次循环的时候不管条件是否满足,均会执行一遍}test_word <- 'Hello, welcome to the third class!'cnt <- 2repeat{  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))}

使用的数据框为:
这里写图片描述
运行情况如下图:
这里写图片描述



本次分享到此结束,欢迎大家交流及批评~~

原创粉丝点击