r-在ddply/dlply中嵌套nlm函数



我需要使用nlm函数对大型数据帧进行分组插值。我在只有一个组的df上使用它没有任何问题:

#example data
df <- data.frame(var= cumsum(sort(rnorm(100, mean=20, sd=4))),
time= seq(from=0,to=550,length.out=100))
#create function
my_function <- function(Cini, time, theta,var){
fy <- (theta[1]-(theta[1]- Cini)*exp((-theta[2]/100000)*(time-theta[3])))
ssq<-sum((var-fy)^2)
return(ssq)
}
th.start <- c(77, 148, 5)   #set starting parameters
#run nlm
my_fitt <- nlm(f=my_function, Cini=400, var = df$var,
time=df$time, p=th.start)

然后,我尝试使用dlply函数在具有多个组的df中应用该函数:

#data with groups
df.2 <- data.frame(var= cumsum(sort(rnorm(300, mean=20, sd=4))),
time= rep(seq(from=0,to=1200,length.out=100),3),
groups=rep(c(1:3),each=100))
#run nlm
library(plyr)
my_fitt.2 <- dlply(df.2, .(groups),
nlm(f=my_function, Cini=400, var  = df.2$var,time=df.2$time, p=th.start))

然而,我得到的信息是:Error in fs[[i]](x, ...) : attempt to apply non-function。我还尝试删除df.2$,在本例中获得Error in time - theta[3] : non-numeric argument to binary operator,并在我的原始df中删除Error in f(x, ...) : object 'time.clos' not found(time.clos是变量之一(。

此外,我想使用dplyr库

library(dplyr)
df.2 %>%
group_by(groups) %>%
nlm(f=my_function, Cini=400, v= var,
time=time, p=th.start)

得到CCD_ 8。可能是什么问题?

考虑基本R的by(tapply的面向对象包装器(,它可以按因子对数据帧进行子集划分,并将子集的数据帧传递到方法中,如nlm调用,所有这些都返回对象列表:

run_nlm <- function(sub_df) nlm(f=my_function, Cini=400, var=sub_df$var, 
time=sub_df$time, p=th.start)
# LIST OF nlm OUTPUTS (EQUAL TO NUMBER OF DISTINCT df$groups)
my_fitt_list <- by(df, df$groups, run_nlm)

我对tidyverse环境没什么帮助,因为我更像是一个基本的R型人。我认为上一次调用中的问题是,将一个组data.frame管道连接到一个以function对象为第一个参数的函数。这是行不通的。

让我向你推荐一种基本的R方法:

df.2 %>% 
split(.$groups) %>% 
lapply(function(xx) nlm(f=my_function, Cini=400, var = xx$var, time=xx$time, p=th.start))

这将生成一个长度为3的list(用于三组(,其中包含您的三个结果。

最新更新