本篇文章由 VeriMake 旧版论坛中备份出的原帖的 Markdown 源码生成
原帖标题为:R 语言 | 函数
原帖网址为:https://verimake.com/topics/223 (旧版论坛网址,已失效)
原帖作者为:dawdler(旧版论坛 id = 64,注册于 2020-08-17 14:01:22)
原帖由作者初次发表于 2021-05-27 15:56:54,最后编辑于 2021-05-27 15:56:54(编辑时间可能不准确)
截至 2021-12-18 14:27:30 备份数据库时,原帖已获得 392 次浏览、0 个点赞、0 条回复
R语言
函数
1. 内置函数
函数,也就是一组共同为特定目标而执行的语句。一般来说,在编写一个功能上有一定复杂性的程序时,我们习惯于将代码划分到不同的函数中,每个函数执行它特定的任务,协同实现最终的目标。
和很多语言一样,R语言也提供了很多内置函数,其中有非常丰富的数学函数。对于内置函数,我们可以在编写程序时直接调用。
以下是一些我们在使用R语言时常用的数学函数:
##some common math functions
#构造数列
#create a sequence of from 32 to 44
print(seq(32,44))
#create a sequence of zeros
print(rep(0,5))
#求平均数
#find mean of numbers from 25 to 82
print(mean(25:82))
#数列求和
#find sum of numbers from 41 to 68
print(sum(41:68))
#求平方根
# sqrt(n), find the square root of n
print(sqrt(25))
#求自然常数的幂
# exp(n), n th-power of the natural constant e
print(exp(1))
#对数函数
# log(m,n), m's logarithm, return n to what power is equal to m
#n is the base number
print(log(2,4)) #n为底数
# log10(m), base number is 10, equivalent to log(m,10)
#相当于lg(m)
print(log10(1000))
#rounding functions
#取整函数
#round(n), round off getting rid of all decimal places
#四舍五入取整数
print(round(5.125))
print(round(5.8125))
#保留m位小数,四舍五入
#round(n,m), round off keeping m decimal places
print(round(5.125,2))
print(round(5.8185,2))
#向上取整
#ceiling(n), round up to integer
print(ceiling(5.125))
#向下取整
#floor(n), round down to integer
print(floor(5.8125))
以上代码的输出结果为:



2. 自定义函数
除了调用已有的内置函数,我们也可以根据自己的需求创建函数,并在程序中调用。以下是关于定义含参数和不含参数函数的两个示例:
#create a function to print squares of numbers in sequences
#不含参数
#每次调用new.function都是在计算1:100这个常数列的和
new.function <- function(){
sum = (1+100)*(100/2)
print(sum)
}
#call the function
new.function()
#含首项、项数、公差三个参数
#用户可以自定义想要求和的数列
new.function <- function(a1, n, d){
sum = n*a1 + n*(n-1)*d/2
print(sum)
}
#call the function
new.function(1,100,1)
new.function(2,80,2)
以上代码的输出结果为:


注意:如果函数体内没有设置输出,只是需要传回一个计算结果或者特定值,使用return()
哦!
到这里为止,关于R语言的基础语法就差不多啦!后面的教程将分为两个方向来展开,一个是大多使用R语言的同学最关心的批量数据读写和绘图,其中讲到列表、因子、数据框等等数据结构的时候也会单开版面具体讲解;另一个方向就是关于R语言的面对对象编程。可能更新进度会略慢一点点~
相关资料:
https://www.runoob.com/r/r-functions.html