Home > OS >  Assigning a weighted random variable to a new column in an R dataframe
Assigning a weighted random variable to a new column in an R dataframe

Time:08-17

I have a Dataframe that looks like this in R:

df1 |date|location|daytype| |----|---|---| |2022-9-1|NT|Thur| |2022-9-2|NT|Fri| |2022-9-3|AP|Sat| |2022-9-4|AP|Sun| |2022-9-5|NT|Mon|

I want to create a new column for either a morning or an afternoon shift based on random weight sampling:

df2 |shift|weight| |---|---| |Morning|0.8| |Evening|0.2|

Is there a way to do this?

df1$shift <- sample(df2, prob = df$weight)

CodePudding user response:

We may need to specify the size as the number of rows of 'df1' and replace = TRUE

df1$shift <-  with(df2, sample(shift, prob = weight, 
    size = nrow(df1), replace = TRUE))
  • Related