求标准误分部需大量重复代码
a=1:8
b=seq(1,10,by=0.5)
c=runif(100,min=0,max=1)
a
b
c
meana=sum(a)/length(a)
vara=sum((a-meana)^2)/(length(a)-1)
stderra=sqrt(vara/length(a))
meanb=sum(b)/length(b)
varb=sum((b-meanb)^2)/(length(b)-1)
stderrb=sqrt(varb/length(b))
meanc=sum(c)/length(c)
varc=sum((c-meanc)^2)/(length(c)-1)
stderrc=sqrt(varc/length(c))
封装代码
##定义求均值
mymean<-function(x){sum(x)/length(x)}
mymean(a)
mymean(b)
mymean(c)
##定义求方差
myvar<-function(x){sum((x-mymean(x))^2)/(length(x)-1)}
myvar(a)
##定义求标准误
stderr<-function(x){sqrt(myvar(x)/length(x))}
stderr(a)
stderr(b)
stderr(c)
stderr1<-function(x){sqrt(var(x)/length(x))}
stderr1(a)
stderr1(b)
实例:定义勾股定理函数
注意:定义函数时可以给多个参数用","分割,函数里面步骤间用“;”分割
sqtest<-function(x, y)
{
z1=x^2;
z2=y^2;
z3=z1+z2;
sqrt(z3)
}
sqtest(3,4)
sqtest(6,8)
给X默认值时,应用函数时不给值就按默认值算,给值时则不按默认值算
sqtest1<-function(x=3, y)
{
z1=x^2;
z2=y^2;
z3=z1+z2;
sqrt(z3)
}
sqtest1(,4)
sqtest1(6,8)
sqtest2<-function(x=3, y=4)
{
z1=x^2;
z2=y^2;
z3=z1+z2;
sqrt(z3)
}
sqtest2()
sqtest2(6,8)
网友评论