Home > Enterprise >  How to save 10 different rnorm() in a vector in R?
How to save 10 different rnorm() in a vector in R?

Time:11-14

I need to create a vector, which elements are 10 different normal-distributed random sequences each of length 150. After that for each of these sequences the minimum-, maximum-, mean- and median-value need be calculated. These 4 statistics need be stored in a vector. All 4-element-statistics-vectors shall be stored in a data frame.

i predefined a vector with a length of 10 and was able to create 10 normal distributions with rnorm() and display them using hist(). However I think I failed to save them in the vector.

data <- vector(length = 10)

for(i in 1:10) {
  data[i] <- hist(rnorm(150, 75, 10))
}

CodePudding user response:

You can get your ten samples like this:

samples <- replicate(10, rnorm(150, 75, 10))

And put their summaries into a data frame like this:

do.call(rbind, lapply(asplit(samples, 2), function(x) {
  data.frame(min = min(x), max = max(x), mean = mean(x), sd = sd(x))
}))
#>         min       max     mean        sd
#> 1  41.63553 107.15836 74.65818 11.691526
#> 2  36.27087 103.41606 74.60017 10.580801
#> 3  53.58147 100.37452 75.35968 10.356784
#> 4  48.44410  98.91955 75.13158 10.403437
#> 5  46.69455 102.77960 73.44792 10.692283
#> 6  52.45185 108.14074 75.42726  9.566448
#> 7  51.96023  98.63533 75.59220 10.520285
#> 8  49.03543 102.96443 73.17830 10.615083
#> 9  45.87507 115.26490 74.54446 10.394427
#> 10 47.32588  96.58989 75.85079 10.282901

Created on 2022-11-14 with reprex v2.0.2

  • Related