且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用户在R程序中指定的功能

更新时间:2023-02-18 12:08:27

首先,错误信息是因为您尚未定义对象 para 全球环境。另一方面,maxLik有一个作为参数的函数,所以不要评估函数,而应该调用它:

  library(maxLik )
#仅以para作为参数定义函数
likfunc< -function(para){
alpha< -para [1]
lambda< -para [2]
#在函数中调用dat,因为它将在全局环境中定义
a< -log(para [1])+ log(para [2])+(para [1] -1)* log (dat $ z)
b return((dat $ d * a)+ b)
}
#您的示例
set.seed(201)
u c #para t z d t)
samp dat< -as.data.frame(samp)
mle< -maxLik(logLik = likfunc,start = c(alpha = 2,lambda = 0.5))
mle


I would like to create a function which can be use for different sets of data. This is my function (I make it as source code):

#Log-likelihood function
likfunc<-function(para,dat){
  alpha<-para[1]
  lambda<-para[2]
  a<-log(para[1])+log(para[2])+(para[1]-1)*log(dat$z)
  b<-para[2]*(dat$z)^para[1]
  return((dat$d*a)+b)
}

Then I try to run the following code (this is 1st set of data):

library(maxLik)
set.seed(201)
u<-runif(20,min=0,max=1) #to simulate t
c<-rexp(20,rate=0.05)
t<-(-log(u)/0.5)^(1/2) #initial vale alpha=2,lambda=0.5
z<-pmin(t,c) 
d<-as.numeric(c>t)     
samp<-cbind(t,c,z,d)
data<-as.data.frame(samp)

mle<-maxLik(logLik=likfunc(para,data),start=c(alpha=2,lambda=0.5))
mle

But the R return: Error in likfunc(para, data) : object 'para' not found

I am doing simulation. Previously I run the function every time when there is a new dataset. Then I get an advice as my code will make the R work more and it take very long time to complete the simulation. Anyone can help on this? Thank you.

First the error message is because you haven't defined object para in the global environment. On the other hand maxLik has a function as argument, so instead of evaluating the function you should just call it:

library(maxLik)
# Define the function only with para as argument
likfunc<-function(para){
alpha<-para[1]
lambda<-para[2]
# Call dat inside the function as it will be defined in the global environment
a<-log(para[1])+log(para[2])+(para[1]-1)*log(dat$z)
b<-para[2]*(dat$z)^para[1]
return((dat$d*a)+b)
}    
# Your example
set.seed(201)
u<-runif(20,min=0,max=1) #to simulate t
c<-rexp(20,rate=0.05)
#para <- c(alpha = 2, lambda = 0.5) #initial value alpha=2,lambda=0.5
t<-(-log(u)/2)^(0.5) 
z<-pmin(t,c) 
d<-as.numeric(c>t)     
samp<-cbind(t,c,z,d)
# dat defined in the global environment
dat<-as.data.frame(samp)
mle<-maxLik(logLik=likfunc,start=c(alpha=2,lambda=0.5))
mle