我有一个大数据,有些适合逻辑增长模型,有些适合指数增长模型。我已经成功地根据我的dlply
代码成功计算了nls回归参数,并根据可以采用多个值的三个因素为数据的每个子集计算了参数。但是,我想添加一个约束,以便对另一组变量定义的某些因子集使用一种nls形式,而对其余变量使用另一种形式。我以为我可以使用if … else
表格,但它似乎不起作用。
这里有一个假人来说明我想做什么:
> library(plyr) > data(iris) iris$form<-"b" iris[iris$Species=="setosa",]$form<-"a" > diris<-dlply(iris, as.quoted(.(Species)), > function(x){ > if(x$form=="a"){ > mean(x$Sepal.Length) > }else{ > median(x$Sepal.Length) > } > })
将其拆分为两个不同的
dlply
函数确实可以,但是我宁愿将它们整齐地放在一起:
diris_mean<-dlply(iris[iris$form=="a",], as.quoted(.(Species)), function(x){ mean(x$Sepal.Length) } ) diris_med<-dlply(iris[iris$form!="a",], as.quoted(.(Species)), function(x){ median(x$Sepal.Length) } )
更新:看来我的虚拟示例太简单了,无法传达我的需求。我不了解
summarise
或mutate
如何工作(来自发布的答案)以能够转换为我的函数。这是我正在使用的功能:
NLmodels <- dlply(cum[form=="logistic growth",], as.quoted(.(region, climate, size)),
function(x) {
essai=try(logis<-nls(freq~1/(1+b*exp(-(c*mid_point))),
start=list(b=170,c=0.1),data=x,control=list(maxiter=200),trace=FALSE))
#if the nls was successful, then calculate values
if(class(essai)!="try-error"){
nls_values<-summary(nls(x$freq~1/(1+b*exp(-(c*mid_point))),
start=list(b=170,c=0.1),
data=x, control=list(maxiter=200)))$parameters
}else {
print("error")
}
}
)
我有一个大数据,有些适合逻辑增长模型,有些适合指数增长模型。我已经成功地基于我的dlply计算了nls回归参数...
我们可以使用dplyr