【问题标题】:I am beginner in R and I'm trying to solve a system of equations but when i run i get error in R [duplicate]我是 R 的初学者,我正在尝试求解方程组,但是当我运行时,我在 R [重复]
【发布时间】:2018-06-22 16:27:34
【问题描述】:
# my error : Error in F[1] <- n/(X[0]) - sum(log(1 + Y^exp(X[1] + X[2] * x))) : replacement has length zero

set.seed(16)

#Inverse Transformation on CDF

n=100

SimRRR.f <- function(100, lambda=1,tau)) {
  x= rnorm(100,0,1)
  tau= exp(-1-x)
  u=runif(100)
  y= (1/(u^(1/lambda)-1))^(1/tau)
  y
}
Y<-((1/u)-1)^exp(-1-x)

# MLE for Simple Linear Regresion

# System of equations

library(rootSolve)
library(nleqslv)

model <- function(X){
  F <- numeric(length(X)) 
  F[1] <- n/(X[0])-sum(log(1+Y^exp(X[1]+X[2]*x)))
  F[2] <- 2*n -(X[0]+1)*sum(exp(X[1]+X[2]*x))*Y^( exp(X[1]+X[2]*x))*log(Y)/(1+ Y^( exp(X[1]+X[2]*x)))

  F[3] <- sum(x) + sum(x*log(Y))*exp(X[1]+X[2]*x) -(X[0]+1)*X[1]*sum(exp(X[1]+X[2]*x)*Y^(exp(X[1]+X[2]*x)*log(Y)))/(1+ Y^( exp(X[1]+X[2]*x)))

# Solution

  F

}

startx <- c(0.5,3,1) # start the answer search here
answers<-as.data.frame(nleqslv(startx,model))

【问题讨论】:

  • 这里还有很多事情要做,但很好。 :)

标签: r statistics rstudio


【解决方案1】:

问题是您在 SimRRR 函数内部定义了 xutauy,但试图在函数外部根据它们定义 Y

使用一个函数,你给它输入,然后你得到输出。在函数完成其工作的过程中定义的所有其他变量最终都会消失。就目前而言,Y 应该是一系列 NA(除非您在处理函数时在全局环境中定义了上述变量......)

尝试以下功能,看看它们是否有效:

# I usually put all my library calls together at the beginning of the script.
library(rootSolve)
library(nleqslv)

x = rnorm(n,0,1) # see below for why this is pulled out.
SimRRR.f <- function(x, lambda=1,tau)) { # 100 can't be by itself in the function call.  everything in there needs to be attached to a variable.
  n <- length(x)
  tau= exp(-1-x)
  u=runif(n)
  y= (1/(u^(1/lambda)-1))^(1/tau)
  y
}
Y_sim = SimRRR.f(n = 100, lambda = 1, tau = 1) # pick the right tau, it's never defined here.

您的第二个函数有更多问题。也就是说,它依赖于x,它没有在任何可以找到的地方定义。要么您需要来自上一个函数的x,要么您真正的意思是X。我将假设您确实需要 x 的值,因为 X 的长度仅为 3。这就是我将其从最后一个函数调用中提取出来的原因 - 我们现在需要它。

[更新]

cmets 中也指出这里的索引是错误的。我以前没有发现(并且F 元素定义正确)。我认为我现在也修复了索引问题:

model <- function(X, Y, x){  # If you use x and Y in the function, define them here.
  n <- length(x)

  F <- numeric(length(X)) 
  F[1] <- n/(X[1])-sum(log(1+Y^exp(X[2]+X[3]*x)))
  F[2] <- 2*n -(X[1]+1)*sum(exp(X[2]+X[3]*x))*Y^( exp(X[2]+X[3]*x))*log(Y)/(1+ Y^( exp(X[2]+X[3]*x)))

  F[3] <- sum(x) + sum(x*log(Y))*exp(X[2]+X[3]*x) -(X[1]+1)*X[2]*sum(exp(X[2]+X[3]*x)*Y^(exp(X[2]+X[3]*x)*log(Y)))/(1+ Y^( exp(X[2]+X[3]*x)))  

# Solution

  F

}

我不熟悉nleqslv 包,但除非定义了将其转换为数据框的方法,否则可能不会那么顺利。我会确保在转换之前一切正常。

startx <- c(0.5,3,1) # start the answer search here
answers <- nleqslv(startx,model, Y = Y_sim, x = x)
answer_df <- as.data.frame(answers)

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2016-01-28
    • 2019-02-20
    • 2022-10-15
    • 2017-06-26
    • 2015-12-24
    相关资源
    最近更新 更多