简体   繁体   中英

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

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM