buckwheats
buckwheats

Reputation: 43

I have defined a vector according to a certain rule. How do I define a function that outputs the vector?

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.

Upvotes: 0

Views: 131

Answers (3)

IRTFM
IRTFM

Reputation: 263301

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

Vf <- Vectorize(f)

Upvotes: 0

Tommy
Tommy

Reputation: 40803

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)

Upvotes: 2

ffriend
ffriend

Reputation: 28472

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))

Upvotes: 1

Related Questions