Search code examples
rmatrixsapply

Generating matrix with normal distribution using 'sapply', in R


Does anybody know how I can generate a 100×10 matrix, with elements drawn from a normal distribution with sd = 1 and mean equal to the column number of the element, while using the function 'sapply'?


Solution

  • set.seed(1)
    m <- sapply(1:10, function(x) rnorm(100, mean = x, sd = 1))    
    
    head(m)
    #>           [,1]     [,2]      [,3]     [,4]     [,5]     [,6]     [,7]     [,8]
    #> [1,] 0.3735462 1.379633 3.4094018 4.893674 6.074441 6.077303 6.658933 7.292432
    #> [2,] 1.1836433 2.042116 4.6888733 2.952702 6.895655 5.703131 8.502425 9.971572
    #> [3,] 0.1643714 1.089078 4.5865884 5.971337 4.397003 4.816758 7.528308 7.910001
    #> [4,] 2.5952808 2.158029 2.6690922 3.616368 4.609132 6.011293 7.542191 7.985983
    #> [5,] 1.3295078 1.345415 0.7147645 5.654145 4.583778 6.991601 6.863327 6.876543
    #> [6,] 0.1795316 3.767287 5.4976616 5.512213 4.624343 7.593967 5.863266 6.655870
    #>          [,9]     [,10]
    #> [1,] 7.913091  8.458597
    #> [2,] 7.173917 10.194321
    #> [3,] 9.995282 10.264423
    #> [4,] 8.988138  8.881265
    #> [5,] 8.400372 10.650953
    #> [6,] 8.822052  8.967100
    

    Created on 2021-02-11 by the reprex package (v1.0.0)