Take a function as an argument
http://cos.name/cn/topic/155239
一个求助引出的冷艳代码
有一个dataset
dataset <- c(3,4,5,6,7,2,3,4,5,6,6,1)
写一个function计算这个数据组每五个数一组的average和range,如果最后一组少于5个数的话写一个note,就是
the average and range of(3,4,5,6,7)
the average and range of(2,3,4,5,6)
the average and range of(6,1)
and a message that in the last group only 2 values
高贵冷艳不知道怎么运行的版本
cos上写代码以冷艳简短著称的月珥给出了示范代码:
dataset <- c(3,4,5,6,7,2,3,4,5,6,6,1)
MyFun=function(num,fun=c(mean,range))
{
if(length(num)%%5!=0)
warning('The last group has less than 5 elements!')
tapply(num,as.integer(seq(1,by=0.2,along.with=num)),fun)
}
lapply(c(mean,range),MyFun,num=1:13)
作者附带的解释:用function类变量做形参的写法对新人来说大概太过丧心病狂了点。但是计算思路个人觉得还是可以模仿一下的:先建立一个步进1/5=0.2的数列,然后强制转换成整数型,就可以快速得到一个每5个元素一组的factor,然后再tapply就行。
单一功能版
dataset <- c(3,4,5,6,7,2,3,4,5,6,6,1)
MyFun=function(data)
{
if(length(data)%%5!=0)
warning('The last group has less than 5 elements!')
tapply(data,as.integer(seq(1,by=0.2,along.with=data)),mean)
}
MyFun(dataset)
dataset
月珥:当然这样就只能用来计算平均值了。要计算range的话把mean改成range即可。
屌丝版
dataset <- c(3,4,5,6,7,2,3,4,5,6,6,1)
myfun <- function(data){
i=1
k=4
data0=NULL
data1=NULL
data2=NULL
data2=c(mean="",min="",max="")
j <- c(seq(1,length(data),by=5))
for(i in j){
data0 <-data[i:(i+k)]
if(length(data)<(i+k)){
print(sprintf('The last group has only %i values!',length(data)%%5))
data0 <-na.omit(data0)
}
data1 <- c(mean(data0),range(data0))
data2 <- rbind(data2,data1)
i=i+k+1
}
colnames(data2)=c("mean","min","max")
rownames(data2)=seq(1,nrow(data2))
return(data2)
}
myfun(dataset)