在某些条件下,我无法在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:
我尝试做的是在规定的条件下随机排除一些行(标记为0)。
有人可以帮帮我吗?
答案 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