MOHAMMED
MOHAMMED

Reputation: 400

R: create a function to generate a specific random variable

I am trying to generate the following vector

n = 13
sparsity = 0.5
p = 3
Delta = c(replicate(p, c(rnorm(round(sparsity*n)/2,3,.5),
                    rnorm(round(sparsity*n)/2,-3,.5),
          rep(0,(n-(round(sparsity*n)))))
))

Obviously, there are three components in the Delta (i.e. N(3,0.5), N(-3,0.5), and zeros). These components are generated p times. The problem I face is that, sometimes, I have to change the settings and I should be very careful about it.

Therefore, I was wondering if it is possible to create a function that can generate the same values. The length of Delta is n*p, so I was thinking about creating a zero vector of the same length then assign some values to specific locations in the vector, but I couldn't figure this out in a concise way.

Upvotes: 2

Views: 175

Answers (3)

SSDN
SSDN

Reputation: 326

as it seems variable sparsity must be < 1 to prevent the error from rep() function. and the length of Delta is not always P*N. at first create variable as

fun <- function(n,sparsity,p){
  myVar = round(n*sparsity)
  if(myVar %% 2 == 1){
    myVar = myVar + 1
  }
  if(myVar > n){
    return(NA)
  }
  Delta = c(replicate(p, c(rnorm(myVar/2,3,.5),
                         rnorm(myVar/2,-3,.5),
                           rep(0,(n-(myVar))))
  ))
  Delta
}
n = 13
sparsity = 0.5
p = 3
fun(n,sparsity ,p)

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101337

What about this (seems not concise enough)

Delta <- c(replicate(
  p,
  replace(
    rep(0, n),
    seq(round(sparsity * n)),
    c(t(matrix(rnorm(round(sparsity * n), c(3, -3), .5), nrow = 2)))
  )
))

Upvotes: 3

MrFlick
MrFlick

Reputation: 206197

I'm not sure that it will make much of a big difference, but you could generate all the numeric values in one go rather than doing replicate. You do have to do a bit of messy indexing, but this will return the same basic result

gen_delta <- function(n, sparsity, p) {
  v <- rep(0, n*p)
  q <- round(sparsity*n)/2
  idx <- c(outer(1:q, n*0:(p-1), FUN = `+`))
  v[idx] <- rnorm(q*p, 3, .5)
  v[idx+q] <- rnorm(q*p, -3, .5)
  v
}

gen_delta(13, 0.5, 3)

Upvotes: 2

Related Questions