2

I am ashamed I need assistance on such a simple task. I want to create 20 normal distributed numbers, add them, and then do this again x times. Then plot a histogram of these sums. This is an exercise in Gilman and Hills text "Data Analysis Using Regression and Multilevel/Hierarchical Models".

I thought this would be simple, but I am into it about 10 hours now. Web searches and looking in "The Art of R Programming" by Norman Matloff and "R for Everyone" by Jared Lander have not helped. I suspect the answer is so simple that no one would suspect a problem. The syntax in R is something that I am having difficulty with.

    > #  chapter 2 exercise 3
    > n.sim <- 10  #  number of simultions
    > 
    > sumNumbers <- rep(NA, n.sim) #  generate vector of NA's
    > for (i in 1:n.sim)  #  begin for loop
     +{
     +     numbers <- rnorm(20,0,1)  
     +     sumNumbers(i) <- sum(numbers) #  defined as a vector bur R 
     +                                   #  thinks it's a function
     + }
 Error in sumNumbers(i) <- sum(numbers) :     
 could not find function "sumNumbers<-"
 > 
 > hist(sumNumbers)    
 Hide Traceback

 Rerun with Debug    
 Error in hist.default(sumNumbers) : 'x' must be numeric     
 3 stop("'x' must be numeric")   
 2 hist.default(sumNumbers)  
 1 hist(sumNumbers) 
 > 
1
  • 1
    You might want to tag with the language you are using in the future. It makes it a lot easier for your question to be seen by the right people. Commented May 17, 2015 at 0:43

2 Answers 2

1

A few things:

  1. When you put parentheses after a variable name, the R interpreter assumes that it's a function. In your case, you want to reference an index of a variable, so it should be sumNumbers[i] <- sum(numbers), which uses square brackets instead. This will solve your problem.

  2. You can initiate sumNumbers as sumNumbers = numeric(n.sim). It's a bit easier to read in simple case like this.

  3. By default, rnorm(n) is the same as rnorm(n,0,1). This can save you some time typing.

Sign up to request clarification or add additional context in comments.

Comments

0

You can replicate an operation a specified number of times with the replicate function:

set.seed(144) # For consistent results
(simulations <- replicate(10, sum(rnorm(20))))
#  [1] -9.3535884  1.4321598 -1.7812790 -1.1851263 -1.9325988  2.9652475  2.9559994
#  [8]  0.7164233 -8.1364348 -7.3428464

After simulating the proper number of samples, you can plot with hist(simulations).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.