在ddply / dlply中嵌套nlm函数

时间:2018-07-31 11:18:32

标签: r dplyr plyr 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 foundtime.clos是变量之一)。

此外,我应该使用dplyr库

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

获得Error in f(x, ...) : unused argument (.)。可能是什么问题?

2 个答案:

答案 0 :(得分:2)

考虑基础R的bytapply的面向对象的包装器),它可以按因数将数据帧子集化,并将子集化的数据帧传递到诸如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)

答案 1 :(得分:1)

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))

这将产生三个结果的list,长度为3(用于三个组)。

相关问题