Creating a table with proportional values

Viewed 24

I have got a data set that looks like this:

COMPANY       DATABREACH        CYBERBACKGROUND
A             1                 2
B             0                 2 
C             0                 1
D             0                 2 
E             1                 1
F             1                 2
G             0                 2  
H             0                 2
I             0                 2
J             0                 2

No I want to create the following: 40% of the cases that the column DATABREACH has the value of 1, I want the value CYBERBACKGROUND to take the value of 2. I figure there must be some function to do this, but I cannot find it.

2 Answers
ind <- which(df$DATABREACH == 1)
ind <- ind[rbinom(length(ind), 1, prob = 0.4) > 0]
df$CYBERBACKGROUND[ind] <- 2

The above is a bit more efficient in that it only pulls randomness for as many as strictly required. If you aren't concerned (11000 doesn't seem too high), you can reduce that to

df$CYBERBACKGROUND <-
  ifelse(df$DATABREACH == 1 & rbinom(nrow(df), 1, prob = 0.4) > 0,
         2, df$CYBERBACKGROUND)

We may use

library(dplyr)
df1 <- df1 %>%
   mutate(CYBERBACKGROUND = replace(CYBERBACKGROUND,
    sample(which(DATABREACH == 0), sum(ceiling(sum(DATABREACH) * 0.4))), 2))
Related