Dipankar Mondal Dipankar Mondal - 1 year ago 59
R Question

Simulate data that satisfy linear equation in R?

I would like to generate data (w1,w2,w3,w4) which satisfies the following equation:

w1+ w2+ w3 + w4 = 1 such that wi >= 0 for all i.

So how would I proceed ?

Answer Source
gend=function(n){#n is the number of such samples you would like to generate.
  D=matrix(NA,n,4)
  for(i in 1:n){
    a=runif(3)
    b=a[2];d=a[3];a=a[1]
    while((b+a)>1)b=runif(1)
    while((b+a+d)>1)d=runif(1)
    D[i,]=c(a,b,d,1-sum(a,b,d))
  }
 D
}
S=gend(10)
S
           [,1]       [,2]        [,3]         [,4]
 [1,] 0.8599033 0.04730250 0.008108873 0.0846853156
 [2,] 0.3181092 0.37239277 0.243917543 0.0655804751
 [3,] 0.4733250 0.07116504 0.145719661 0.3097903084
 [4,] 0.9482858 0.04967905 0.001082051 0.0009531255
 [5,] 0.7291447 0.16336750 0.106824697 0.0006631124
 [6,] 0.1896754 0.60669666 0.062790600 0.1408372964
 [7,] 0.8452493 0.12875891 0.022590556 0.0034012373
 [8,] 0.4452403 0.52793687 0.011378945 0.0154438773
 [9,] 0.4618185 0.23065407 0.224276892 0.0832504972
[10,] 0.2191794 0.09512862 0.110790973 0.5749009629

rowSums(S)
 [1] 1 1 1 1 1 1 1 1 1 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download