在约束下生成随机虚拟

在某些条件下,我无法在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 = "val2"或var2 = "val3"则var3 = 1

  • 如果var2 = "val1" AND var1 = "a"则必须随机分配n次(比如说3)值1,否则为0 .

  • 如果var2 = "val1" AND var1!= "a"则var3 = 1

我想要做的是在定义的条件下随机排除一些行(标记为0) .

请问有人可以帮助我吗?

回答(1)

2 years ago

好像你可以从制作所有 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