R语言-函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lovely_J/article/details/82053845

定义函数:
f <- function(x){
语句;
return value
}
调用:
f(x)

> f <- function(x, y){
+   xrow <- dim(x)[1]
+   xcol <- dim(x)[2]
+   yrow <- dim(y)[1]
+   ycol <- dim(y)[2]
+   if(xcol != yrow){
+     print('两个矩阵维数不相同')
+    return(0)
+   }
+   mat <- matrix(0,nrow = dim(x)[1],ncol = dim(y)[2])
+   for(i in c(1:xrow))
+     for(j in c(1:ycol))
+       mat[i,j] <- sum(x[i,]*y[,j])
+   return(mat)
+ }
> f(mat1,mat2)
     [,1] [,2]
[1,]   48   48
[2,]   64   64
> mat1 %*% mat2
     [,1] [,2]
[1,]   48   48
[2,]   64   64

> mat3 <- matrix(c(1:4),nrow = 2)
> f(mat1,mat3)
[1] "两个矩阵维数不相同"
[1] 0

递归调用函数

> Fib <- function(a){
+    a <- as.numeric(a)
+    #为了保证计算正确,将传入的参数进行数据规范的处理
+    if(a <= 2)
+      return(1)
+    else
+      return(Fib(a-1)+Fib(a-2))
+  }
>  
>  for(i in c(1:10)){
+    print(Fib(i))
+  }
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
[1] 21
[1] 34
[1] 55

猜你喜欢

转载自blog.csdn.net/lovely_J/article/details/82053845