0

the rule is: for(i in 1:10){v[i]=f(q,m)}. f(q,m) is a function that generates random outputs in an interval according to the inputs q, m. 'v' is the vector.

After specifying the components of v that way, I can type v, and return the vector. What I would like to be able to do is define a function that takes the inputs q,m and returns the vector, v.

The reason is eventually I want to be able to graph the mean of v, ranging over the variable q. but i need a function that returns v first, i think. So any advice on how to define such a function would be greatly appreciated.

Thanks.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
buckwheats
  • 43
  • 4
  • Does `runif` already do what you want? – John Colby Apr 14 '12 at 22:13
  • Welcome to Stack Overflow. When you pose a problem it helps to provide us with a minimally reproducible example as described [(HERE)](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). When you give code you should define what everything is since we don't know what f is. This makes your question useful for others searching the thread and not just specific to you. It also helps to give us an example of what the output should be. – Tyler Rinker Apr 14 '12 at 22:23

3 Answers3

2

Generating values is elegantly done using the apply family of functions. vapply is lesser known, but more efficient than sapply, so I promote it here. The numeric(1) specifies what the result of f is expected to be:

# Emulating your function f
f <- function(q, m) runif(1, q, m)

# Generator function
g <- function(n=10, q, m) vapply(seq_len(n), function(i) f(q, m), numeric(1))

# Try it out
q <- 3
m <- 5
v <- g(10, q, m)

# or, if f is defined as above, simplify to:
v <- runif(10, q, m)
Tommy
  • 39,997
  • 12
  • 90
  • 85
1

Exactly following your code:

makeVector <- function(q, m) { 
  v <- c()
  for (i in 1:10) {
    v[i] <- f(q, m)
  }
  v
}

Or, more elegant:

makeVector <- function(q, m) sapply(1:10, function(q, m) f(q, m))
ffriend
  • 27,562
  • 13
  • 91
  • 132
0

It's probably equivalent to the solutions offered (and doesn't fully address the missing details) but have you tried?

Vf <- Vectorize(f)
IRTFM
  • 258,963
  • 21
  • 364
  • 487