Kay Kay - 22 days ago 7
R Question

append values by dataframe row in a loop

I'm running models with various initial values, and I'm trying to append values (3 estimators) by rows to a dataframe in a loop. I assign values to estimators within the loop, but I can't recall them to produce a dataframe.

My code:

f
is the model for the estimation. Three parameters: alpha, rho, and lambda in the model. I want to output these 3 values.

library("maxLik")

f <- function(param) {
alpha <- param[1]
rho <- param[2]
lambda <- param[3]
u <- 0.5 * (dataset$v_50_1)^alpha - 0.5 * lambda * (dataset$v_50_2)^alpha
p <- 1/(1 + exp(-rho * u))
logl <- sum(dataset$gamble * log(p) + (1 - dataset$gamble) * log(1 - p))
}


df <- data.frame(alpha = numeric(), rho = numeric(), lambda = numeric())

for (j in 1:20) {
tryCatch({
ml <- maxLik(f, start = c(alpha = runif(1, 0, 2), rho = runif(1, 0, 4), lambda = runif(1,
0, 10)), method = "NM")

alpha[j] <- ml$estimate[1]
rho[j] <- ml$estimate[2]
lambda[j] <- ml$estimate[3]

}, error = function(e) {NA})
}
output <- data.frame(alpha, rho, lambda)


error occurs:

Error in data.frame(alpha, rho, lambda) : object 'alpha' not found


Expected output

alpha rho lambda
0.4 1 2 # estimators append by row.
0.6 1.1 3 # each row has estimators that are estimated
0.7 1.5 4 # by one set of initial values, there are 20
# rows, as the estimation loops for 20 times.

Answer Source

I am running an example, by changing the function f

library("maxLik")

t <- rexp(100, 2)
loglik <- function(theta) log(theta) - theta*t


df <- data.frame(alpha = numeric(), rho = numeric(), lambda = numeric())

for (j in 1:20){
  tryCatch({
    ml <- maxLik(loglik, start = c(alpha = runif(1, 0, 2), rho = runif(1, 0, 4), 
                              lambda = runif(1, 0, 10)), method = "NM")

    df <- rbind(df, data.frame(alpha = ml$estimate[1], 
                               rho = ml$estimate[2], 
                               lambda = ml$estimate[3]))
    # I tried to append values for each column         
  }, error = function(e) {NA})}

> row.names(df) <- NULL
> head(df)
     alpha      rho   lambda
1 2.368739 2.322220 2.007375
2 2.367607 2.322328 2.007093
3 2.368324 2.322105 2.007597
4 2.368515 2.322072 2.007334
5 2.368269 2.322071 2.007142
6 2.367998 2.322438 2.007391