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))}
使用的数据框为:
运行情况如下图:
本次分享到此结束,欢迎大家交流及批评~~
阅读全文
0 0
- R语言学习笔记(四)流程函数及自定义函数
- R语言学习笔记(概念、公式及R函数)
- R语言与函数估计学习笔记(函数展开)
- R语言:自定义函数
- Go语言学习笔记(四)函数
- R语言layout函数学习笔记
- R语言学习笔记-概率函数
- R语言学习笔记-统计函数
- R语言学习笔记——函数
- 【R语言学习笔记】rep函数
- R语言学习 入门及常用函数(一)
- R语言学习笔记(四)
- R语言学习笔记(四)
- R语言学习笔记(四)
- R语言-编写自定义函数
- R语言自定义函数及基本分支循环结构
- R语言笔记-sample()函数
- R语言与函数估计学习笔记(函数模型的参数估计)
- redis详解-(1)redis的安装
- 23.Oracle杂记——Oracle常用动态视图v$log
- 24.Oracle杂记——Oracle常用动态视图v$logfile
- Shiro整合Spring实现登录验证和授权之入门
- zabbix自定义监控,统计nginx服务器的pv uv
- R语言学习笔记(四)流程函数及自定义函数
- USB OTG原理和 ID 检测原理
- 初学C语言的感受
- 25.Oracle杂记——Oracle常用动态视图v$parameter
- BufferedReader笔记与综合案例
- 关于linux断电安全
- Ajax-Jquery的Ajax技术(三)
- 26.Oracle杂记——Oracle常用动态视图v$process
- 数值分析之 拉格朗日插值、牛顿插值、分段线性插值实现