1

With a vector of values, I want each value to be called on a function

values = 1:10
rnorm(100, mean=values, sd=1)

mean = values repeats the sequence (1,2,3,4,5,6,7,8,9,10). How can I get a matrix, each with 100 observations and using a single element from my vector? ie:

rnorm(100, mean=1, sd=1)
rnorm(100, mean=2, sd=1)
rnorm(100, mean=3, sd=1)
rnorm(100, mean=4, sd=1)
# ...
TVB22
  • 47
  • 3

4 Answers4

5

An option is lapply from base R

lapply(1:10, function(i) rnorm(100, mean = i, sd = 1))
akrun
  • 874,273
  • 37
  • 540
  • 662
5

It's not clear from your question, but I took it that you wanted a single matrix with 10 rows and 100 columns. That being the case you can do:

matrix(rnorm(1000, rep(1:10, each = 100)), nrow = 10, byrow = TRUE)

Or modify akrun's answer by using sapply instead of lapply

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
4

Or Map from base R:

Map(function(i) rnorm(100, mean = i, sd = 1), 1:10)
TarJae
  • 72,363
  • 6
  • 19
  • 66
3

Using map I can apply a function for each value from the vector values

library(purrr)

values = 1:10
map_dfc(
  .x = values,
  .f = ~rnorm(100,mean = .x,sd = 1)
  )

In this case I will have a data.frame 100x10

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32