Oliver Wang
Oliver Wang

Reputation: 11

How to generate a random variable using values of another random variable as its parameter

I have a code that generates 5 random variables from a specified distribution(e.g. uniform) and placed it in the first column of a 5x2 matrix

my.data <- data.frame(matrix(nrow = 5, ncol = 2))
colnames(my.data) <- c("unif", "norm")
set.seed(1)
my.data[, 1] <- runif(5)

which looks something like this

       unif norm
1 0.2655087   NA
2 0.3721239   NA
3 0.5728534   NA
4 0.9082078   NA
5 0.2016819   NA

I want to use the generated random variables as the parameter of another distribution(e.g. normal), that is, I want to sample from a normal distribution with mean equal to the value of the uniformly distributed random variables and standard deviation equal to the the value of random variable*0.1.

my.data[, 2] <- rnorm(1, mean = my.data$unif, sd = my.data$unif*0.1)
my.data[, 2] <- rnorm(1, mean = my.data[,1], sd = my.data[,1]*0.1)

I've written the code in two ways but obtained the same results.

       unif      norm
1 0.2655087 0.2992928
2 0.3721239 0.2992928
3 0.5728534 0.2992928
4 0.9082078 0.2992928
5 0.2016819 0.2992928

Where all the values in column two are identical. How can I change the code so I can generate a random variable in the second column using values from the first column as its parameters?

Upvotes: 1

Views: 586

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You are generating only 1 number in rnorm which is being recycled for all the values. Generate numbers as much as the number of rows in your data.

my.data[, 2] <- rnorm(nrow(my.data),  mean = my.data$unif, sd = my.data$unif*0.1)

Upvotes: 1

Related Questions