下面是自定义的方差函数,该函数的作用是:计算向量x的方差
set.seed(11)
x <- rnorm(20, mean = 60, sd = 15)
weight <- x
height <- rnorm(20, mean = 170, sd = 20)
variance <- function(x){
n <- length(x)
mean_x <- mean(x) #计算平均数
variance <- sum((x-mean_x)^2)/(n-1) #计算方差
return(variance)
}
接下来,我们将自定义的方差计算函数’variance()’与基础函数’var()’的结果进行对比
print("自定义函数计算得到的方差:")
## [1] "自定义函数计算得到的方差:"
print(variance(x))
## [1] 161.7275
print("基础函数计算得到的方差:")
## [1] "基础函数计算得到的方差:"
print(var(x))
## [1] 161.7275
经比较,二者计算得到的结果相同
下面是自定义的BMI计算函数,它的作用是:将输入的身高height(cm)与体重weight(kg)计算之后的BMI结果返回
BMI<-function(weight,height){
height_m <- height/100#转换为米
BMI <- weight/(height_m^2)
return(BMI)
}
print("BMI结果:")
## [1] "BMI结果:"
print(BMI(weight,height))
## [1] 20.91802 20.97748 14.34488 12.62005 26.42113 15.88594 28.89244 28.99301
## [9] 21.63458 19.88541 21.74426 23.94772 10.95752 29.30160 18.35813 18.63900
## [17] 20.49119 18.16328 20.53568 18.87035
下面是自定义的大于阈值的均值计算函数,该函数的作用是:对于给定的向量x和阈值threshold(默认值60),求出x中所有大于该阈值的元素的均值
mean_above_threshold <- function(x,threshold=60){
filtered_values <- x[x>threshold]
if (length(filtered_values)>0){
mean_value <- mean(filtered_values)
}else{
mean_value <- NA #如果没有大于阈值的元素,返回NA
}
return(mean_value)
}
print("大于阈值的元素均值为:")
## [1] "大于阈值的元素均值为:"
print(mean_above_threshold(x,threshold=60))
## [1] 70.13426