我需要使用该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)
然后,我尝试使用该函数在具有多个组的 df 中应用该dlply
函数:
#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 (是变量之一)中删除df.2$
, 获取。Error in time - theta[3] : non-numeric argument to binary operator
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)
获得Error in f(x, ...) : unused argument (.)
. 可能是什么问题呢?