函数语法
函数名<-function(parameters){
statemens
return(expression)}
代码语言:javascript复制printLine <- function () {
print("--------------------------------------------");
}
#函数的调用
printLine();
#错误:无参函数,有参调用
printLine("parameter");
printNLines <- function (n) {
for(i in 1:n) {
print("--------------------------------------------");
}
}
#错误:有参函数,无参调用
printNLines()
printNLines(3)
printNLines <- function (n=1) {
for(i in 1:n) {
print("--------------------------------------------");
}
}
#正确:有参函数,因为有默认值,可以无参调用
printNLines()
#也可以有参数调用
printNLines(3)
printInfo <- function (name, age) {
print(paste("name is: ", name, ", age is: ", age, sep=""))
}
printInfo("KEN", 18)
printInfo(age=18, name="KEN")
printInfo <- function (name, age, ...) {
print(paste("name is: ", name, ", age is: ", age, sep=""));
otherParames = list(...);
for(key in names(otherParames)) {
print(paste(key, " is: ", otherParames[key], sep=""));
}
}
printInfo("KEN", 18, height="178CM", weight="75KG", sex="男");
data <- read.csv("data.csv", sep=",", fileEncoding='utf8');
summary(data[,3])
#summary加强版
summaryEx <- function(column) {
s <- summary(column)
#方差
s[['var']] <- var(column);
#标准差
s[['sd']] <- sd(column);
#s #直接写个s也可以替代下面的语句
return (s);
}
summaryEx(data[, 3])