我是靠谱客的博主 潇洒毛衣,最近开发中收集的这篇文章主要介绍R语言入门(26)-函数(function),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

> f <- function() {
+ ## This is an empty function
+ } 

> ## Functions have their own class
> class(f)
[1] "function"

> ## Execute this function  
> f()
NULL

> f <- function() {
+ cat("Hello, world!n")
+ } 
> f()
Hello, world!

this function = cut and print????

prints the message “Hello, world!” to the console a number of times indicated by the argument num.
> f <- function(num) {
+ for(i in seq_len(num)) {
+ cat("Hello, world!n") 
+ } 
+ } 
> f(3)
Hello, world!
Hello, world!
Hello, world!

this function returns the total number of characters printed to the console????

returns the number of characters printed to the console
> f <- function(num) {
+     hello <- "Hello, world!n"
+     for(i in seq_len(num)) {
+         cat(hello)
+     } 
+     chars <- nchar(hello) * num
+         chars
+} 
> meaningoflife <- f(3)
Hello, world!
Hello, world!
Hello, world! 
> print(meaningoflife)
[1] 42

 function的调用如果没有arg,就会报错。为了防止使用时我们忘记加入arg,可以在一开始定义function的时候就set一个default value。????

has one formal argument named num with a default value of 1.
The formal arguments are the arguments included in the function definition.
The formals() function returns a list of all the formal arguments of a function.
> f <- function(num = 1) {                 # set the default value for num to be 1
+        hello <- "Hello, world!n"        
+        for(i in seq_len(num)) {
+        cat(hello)
+        } 
+        chars <- nchar(hello) * num
+        chars
+ } 

> f()               ## Use default value for 'num' 
Hello, world! [1] 14
> f(2)              ## Use user-specified value
Hello, world!
Hello, world! 
[1]28

最后

以上就是潇洒毛衣为你收集整理的R语言入门(26)-函数(function)的全部内容,希望文章能够帮你解决R语言入门(26)-函数(function)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部