Georgia Dickinson
Georgia Dickinson

Reputation: 1

store function results in a vector

I have a function here that takes samples, it works however I'm struggling to store the samples taken in a vector so that I may plot them; here is my function below:

InvCDF = function(n, sd) {
for (i in 1:n) {
u=runif(1, min = 0, max = 1)
x = sqrt(-2*(sd^2)*log(1-u))
print(x)
}
}

I have tried creating a vector of 0's initially with

x = vector(mode="numeric",length=n)

then somehow fill in these 0's with the samples taken but it isn't working.

If someone could please assist with with storing my print(x) values in a vector I would be so happy

Upvotes: 0

Views: 3538

Answers (2)

Chirayu Chamoli
Chirayu Chamoli

Reputation: 2076

You need to create a list for storing all the iteration of x. then you need to call the required function to get those values i.e. here xx will store the results. As suggested by Roland, growing a list in the R is a very slow operation. You should use the vectorized approach when ever possible.

InvCDF = function(n, sd) {
    x=list()
    for (i in 1:n) {
        u=runif(1, min = 0, max = 1)
        x[[i]] = sqrt(-2*(sd^2)*log(1-u))           
    }
    unlist(x)
}
xx=InvCDF(100,19)

You could pre-define a vector and use it in a loop. This which would be much faster than list operations.

x <- numeric(n)
InvCDF = function(n, sd) {
    for (i in 1:n) {
        u=runif(1, min = 0, max = 1)
        x[i] = sqrt(-2*(sd^2)*log(1-u))
    }
    x
}

Upvotes: 1

Roland
Roland

Reputation: 132969

There really is no need to use a loop here. runif is vectorized as are sqrt, log etc.

InvCDF = function(n, sd) {
  u <- runif(n, 0, 1)
  sqrt(-2*(sd^2)*log(1-u))
}

set.seed(1) # for reproducibility
InvCDF(5, 1)
#[1] 0.7855916 0.9647926 1.3043220 2.1855104 0.6711903

Upvotes: 1

Related Questions