Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3405430
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T05:30:16+00:00 2026-05-18T05:30:16+00:00

I have the following function that draws some data from a chi-squared distribution and

  • 0

I have the following function that draws some data from a chi-squared distribution and compares the distribution of X to a known chi-squared distribution using maximum likelihood. This procedure is simulated nSims times. (I compare these results to results from a permutation test, but that code is excluded.)

chi2c <- function(xdf=2, yObs=100, xObs=100, nSims=1000, nPerm=500, alpha=0.05){
  simResults <- sapply(1:nSims, function(x){
    # Draw variables
    x  <- rchisq(xObs, df=xdf)
    # Other variables not relevant here
    # [[snip]]

    # Permutation test
    # [[snip]]

    # Calculate the statistics necessary for maximum likelihood
    n       <<- length(x)
    sumlx   <<- sum(log(x))
    sumx    <<- sum(x)
    # Calculate the maximum likelihood estimate
    dfhat   <- optimize(f=c2ll, interval=c(1, 10), maximum=TRUE)$maximum
    # Calculate the test statistic: -2 times the log likelihood ratio
    llr     <- -2 * (c2ll(2) - c2ll(dfhat))
    # Compare the test statistic to its asymptotic dist: chi-squared
    lReject <- llr > qchisq(1 - alpha, df=1)

    # Provide the results
    # [[snip]]
  })
  # Calcuate means across simulations
  rowMeans(simResults)
}

This function calls c2ll, the chi-squared likelihood function

c2ll <- function(dfHat){
  -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + 
  (dfHat/2 - 1) * sumlx - sumx/2
}

This function does just what I would like and is accurate, but I don’t understand why I have to set the maximum likelihood statistics (n, sumlx, and sumx) globally to get it to work; optimize doesn’t find them if I only set them inside the function using <-. I tried setting them inside of optimize, but that didn’t work either. Thanks for your help.

Charlie

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T05:30:17+00:00Added an answer on May 18, 2026 at 5:30 am

    R has lexical scoping, which means that functions look for variables in the environment in which they were defined. c2ll is defined in the global environment, so it doesn’t see your definitions of n, sumx, and sum1x inside the function. S on the other hand uses dynamic scoping, which behaves as you expect (i.e. it looks for variables in the scope in which it was called). Computer scientists generally believe that dynamic scoping was a dead-end bad idea, and that lexical scoping is the way to go.

    As a practical matter, what can you do about this?

    Well, there are a couple options…

    First, you can define your function locally:

    n       <- length(x)
    sumlx   <- sum(log(x))
    sumx    <- sum(x)
    c2ll <- function(dfHat){
        -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + (dfHat/2 - 1) * sumlx - sumx/2
    }
    dfhat   <- optimize(f=c2ll, interval=c(1, 10), maximum=TRUE)$maximum
    

    Second, you can have c2ll take additional parameters, and pass those parameters through optimize.

    #in global env
    c2ll <- function(dfHat,n,sum1x,sumx){
      -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + 
      (dfHat/2 - 1) * sumlx - sumx/2
    }
    
    #...
    #in function
    n       <- length(x)
    sumlx   <- sum(log(x))
    sumx    <- sum(x)
    dfhat   <- optimize(f=c2ll, interval=c(1, 10), n=n,sum1x=sum1x,sumx=sumx, maximum=TRUE)$maximum
    

    Both are clean options that preserve the encapsulation of your functions.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following function that is pulling data from a database. The ajax
I have the following situation: I have a certain function that runs a loop
I have a function that gives me the following warning: [DCC Warning] filename.pas(6939): W1035
I have a calc function in java script that takes three integer parameters, following
I have a custom control that has the following prototype. Type.registerNamespace('Demo'); Demo.CustomTextBox = function(element)
So: I have the following function, adapted from a formula found online, which takes
I have the following function that was written by someone else, however I am
If I have the following function that iterates through a json response object (val2):
I have the following Javascript function that should return an array of groups that
I have the following function: CREATE FUNCTION fGetTransactionStatusLog ( @TransactionID int ) RETURNS varchar(8000)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.