[英]R code to estimate parameters from non-linear function
Suppose I have a data set. 假设我有一个数据集。 There are some categorical variables and some numerical variables. 有一些分类变量和一些数值变量。 I want to estimate the parameters of a model e^{X'b}
for every categories and others. 我想估计每个类别和其他类别的模型e^{X'b}
的参数。 I am trying to do it in R code. 我想用R代码做。 I need to do it by creating design matrix for categorical variables like age==2
and age==3
, where considering age==1
as reference category. 我需要通过为age==2
和age==3
等分类变量创建设计矩阵来实现,其中将age==1
作为参考类别。 But this program is not running and giving errors. 但是这个程序没有运行并且出错。 What is the problem? 问题是什么?
sex <- c("F","M","F","M","F","M")
age <- c(1,3,2,3,1,2) # categorical variable with three age categories
age <- as.factor(age)
dat <- data.frame(sex,age)
myfun <- function(par, data){
xx <- data
func <- exp(par[1]*(xx$age==2)+par[2]*(xx$age==3)+par[3]*factor(xx$sex))
return(-func)
}
optim(myfun, par=c(0.1,0.4,0.7), data=dat)
Your function myfun
returns a vector of length 6 (because you multiply with xx$sex
). 你的函数myfun
返回一个长度为6的向量(因为你乘以xx$sex
)。 It needs to be of length 1. Also, the optim
function takes the par
first and the function as second parameter. 它必须是长度为1.此外, optim
函数将par
作为第一个参数,将函数作为第二个参数。
EDIT: You need to rewrite your function to return a single value. 编辑:您需要重写您的函数以返回单个值。 -exp(X'b)
is a vector of length of your observations. -exp(X'b)
是观察长度的向量。 Maybe this goes in your direction: 也许这会朝你的方向发展:
myfun1 <- function(par, data) {
xx <- matrix(c(as.numeric(dat$sex), age, rep(1, nrow(dat))), ncol=3)
sum(-exp(xx %*% par))
}
optim(c(0.1,0.4,0.7), myfun1, data=dat)
Note that it would be more efficient to pass xx
to optim
since the calculation of xx
is independent of the iteration. 请注意,将xx
传递给optim
会更有效,因为xx
的计算与迭代无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.