> 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)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复