在约束下生成随机虚拟

时间:2017-03-01 22:02:17

标签: r

在某些条件下,我无法在R中生成以下虚拟变量。

var1<-c("a","b","c","a","a","a","b","c","b","a")
var2<-c("val1","val1","val1","val1","val2","val1","val3","val3","val2","val1")
db<-data.frame(cbind(var1,var2))

我想根据以下规则生成列var3:

  • 如果var2 =&#34; val2&#34; OR var2 =&#34; val3&#34;然后var3 = 1
  • 如果var2 =&#34; val1&#34; AND var1 =&#34; a&#34;然后必须随机分配n次(让#3说3)值1,否则为0。
  • 如果var2 =&#34; val1&#34; AND var1!=&#34; a&#34;然后var3 = 1

我尝试做的是在规定的条件下随机排除一些行(标记为0)。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

似乎你可以从制作所有var3 1开始,然后只制作符合第二个条件零的那个

db$var3 = 1
x = which(db$var2 == "val1" & db$var1 == "a") #Get indices where 2nd condition is met
db$var3[sample(x, length(x) - 3)] = 0 #Assign 0 all indices in x except 3