R function to draw by row based on changing normal distribution
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have a data frame in the following format:

NAME, ESTIMATE, SE

John, 10.2, 0.3

Mary, 11.1, 0.2

William, 13.2, 0.1

James, 10.9, 0.3

I would like a function that creates a new data frame with estimates for each NAME, with the estimate drawn from a normal distribution (rnorm()) with a mean of ESTIMATE and a standard deviation of SE. Each row should thus have an estimate drawn from a distribution defined by the other variables in the row.

I would like to repeat this function 10,000 times, creating a data frame with estimates for each name for each of the 10,000 repetitions.

@M_TG let me know if I should improve or redo my solution
SirYummy 4 months ago
4 months ago

Crowdsource coding tasks.

1 Solution


"
This function creates a new data frame with estimates for each NAME,  
with the estimate drawn from a normal distribution (rnorm()) with a mean of  
ESTIMATE and a standard deviation of SE
Example usage:
    row_list <- list(NAME = 'John', ESTIMATE = 10.2, SE = 0.3)
    draw_norm_frame(row_list)
Output:
   NAME ESTIMATE  SE     NORM
   1 John  10.2   0.3    10.49831
  "  
draw_norm_frame <- function(row) {  
    row <- as.list(row)  
    norm <- rnorm(1, mean = row$ESTIMATE, sd = row$SE)  
    df <- data.frame(NAME=row$NAME, ESTIMATE=row$ESTIMATE, SE=row$SE, NORM=norm)  
    # print(df)  
    return(df)  
}