简体   繁体   English

R代码从非线性函数估计参数

[英]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==2age==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.

相关问题 R 中非线性优化的 Bootstrap 参数估计:为什么它与常规参数估计不同? - Bootstrap parameter estimate of non-linear optimization in R: Why is it different than the regular parameter estimate? 从 excel 到 R 的非线性优化 - Non-linear optimization from excel to R 对 R 中的非线性 function 进行线性回归 - Do a linear regression on a non-linear function in R R中具有任意数量的拟合参数的非线性最小二乘 - Non-linear least squares with arbitrary number of fitting parameters in R 如何在 R 中优化具有非线性约束的非线性目标函数? - How to optimize a non-linear objective function with non-linear constraints in R? 在R中使用非线性函数的分段非线性回归 - Piecewise non-linear regression using non-linear function in R R中的非线性优化 - Non-linear optimization in R R 中的优化 - 具有非线性约束的非线性效用 function - Optimization in R - nonlinear utility function with non-linear constraints 使用fitModel函数进行R非线性模型拟合 - R non-linear model fitting using fitModel function R 中是否有 package 有助于将非线性 function(高斯)拟合到数据? - Is there a package in R that helps fit a non-linear function (guassian) to data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM