R语言中如何编写自己的函数初步入门
一、循環與控制
循環:
for(i in 1:10) print("hello world")
i<-10
while(i>0){
print(i);
i<-i-1;
}
控制
if()
if() else
ifelse(判斷,true,false)
switch(type,。。。)
二、用戶自定義函數
mystats <- function(x, parametric=TRUE, print=FALSE) {
? if (parametric) {
? ? center <- mean(x); spread <- sd(x)?
? } else {
? ? center <- median(x); spread <- mad(x)?
? }
? if (print & parametric) {
? ? cat("Mean=", center, "\n", "SD=", spread, "\n")
? } else if (print & !parametric) {
? ? cat("Median=", center, "\n", "MAD=", spread, "\n")
? }
? result <- list(center=center, spread=spread)
? return(result)
}
如何調用我們自己編寫的函數
set.seed(1234)
x <- rnorm(500) 生成符合正態分布500個元素
y <- mystats(x)
y <- mystats(x, parametric=FALSE, print=TRUE)
下面是一個關于switch函數的例子
mydate <- function(type="long") {
? ? switch(type,
? ? long = ?format(Sys.time(), "%A %B %d %Y"),?
? ? short = format(Sys.time(), "%m-%d-%y"),
? ? cat(type, "is not a recognized type\n"))
}
mydate("long")
mydate("short")
mydate()
mydate("medium")
總結
以上是生活随笔為你收集整理的R语言中如何编写自己的函数初步入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3-10 Pandas的数据规整
- 下一篇: Swift QQ授权登录 坑集