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)
然后,我尝试使用该函数在具有多个组的 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 (.)
. 可能是什么问题呢?
解决方案
考虑基本 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)
推荐阅读
- google-cloud-platform - 为什么我无法访问 GCP 活动云 shell?
- c# - 消除字符串中的空格
- node.js - 在引用具有不同本地字段的同一表的聚合中使用两个“查找阶段”
- python - SQLAlchemy 加入关联表
- python - 添加 CSS 文件后出现黑屏
- php - PHP7.3:如何在不在子类中重新声明的情况下,继承具有最大可能范围的受保护静态属性?
- mysql - 根据项目从两个 sql 表中求和和差异 - laravel
- css - 在 Safari 中垂直拉伸的图像,父容器作为 display flex
- c++ - 我应该将结构用作 C++ 中的参数化构造函数吗?
- android - 如何为电子商务 Android 应用程序制作管理面板或管理应用程序