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

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))
}

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



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值