R函数编写基础

编写函数:
第一部分:
1 print("str")##打印函数,打印出字符内容
2 sprintf("hello,%s","yjz")##%s是占位符,。
3 函数参数以及函数调用:
hello.persion<-function(first,last)
{
    print(sprintf("hello %s %s",first,last))
}
4 缺省参数
hello.persion<-function(first,last="Rainbow")
{
    print(sprintf("hello %s %s",first,last))
}
#############
> hello.persion("yjz")
[1] "hello yjz Rainbow"
>
#############
5 额外参数
hello.persion<-function(first,last="Rainbow",...)
{
    print(sprintf("hello %s %s",first,last))
}
#########
> hello.persion("yjz","rain","bow")
[1] "hello yjz rain"
>
#########
6 返回值
double.num<-function(x)
{
    return(x*5)
}
#########
> double.num(10)
[1] 50
>
#########
6 do.call
在do.call中,我们可以指定函数名称以及函数参数.
run.this<-function(x,func=mean)
{
    do.call(func,args=list(x))
}
#########
> run.this(1:10)
[1] 5.5
#########
do.call(functionName,args=list(paramter1,paramter2))
##在该函数内部,填写函数名字,例如mean求平均值函数,args是参数列表,就是掉用的mean函数所需要的函数参数。
第二部分:控制语句
1 if 跟else 语句
if(x)
{
    print("")
}
else
{
    print("")
}
2 switch语句
use.switch<-function(x)
{
    switch(x,
        "a"="first",
        "b"="second",
        "c"="last")
}
###########
> use.switch("a")
[1] "first"
>
###########
3 ifelse语句
if(1==1,"yes","no")###第一个参数表达式是条件,第二个是返回真值要展现的结果,第三个参数是返回加值要展现的结果
4 复合检查:
a<-c(1,1,0,1)
b<-c(2,1,0,1)
ifelse(a==1&b==1,"yes","no")
###############
> a<-c(1,1,0,1)
> b<-c(2,1,0,1)
> ifelse(a==1&b==1,"yes","no")
[1] "no"  "yes" "no"  "yes"
>
> ifelse(a==1&&b==1,"yes","no")
[1] "no"

该复合检查,&是挨个比较向量中的每各元素
&&只比较一个,即最左边的那个
################
3 第三部分:迭代方式##for循环跟while循环
for(i in 1:100)
{
    print(i)
}
while(i<=100)
{
    print(i)
    x<-x+1
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值