How to Achieve Randomly Select One Role Data Among Several Roles with Different Weight (sample_n not working)

Hello Everyone,

I would like to achieve one function in R and not sure if there is an existing function in the community so that I don't need to program it by myself. Basically, as you can see in the attached image, I have several people with different personID (3, 4 and 5 in the image). There are multiple roles for every personID with a different weightPercent. I want R to do a random selection based on the weightPercent so that only one role will remain. For instance, for personID 4, I only want one role of data left after R did the selection, and lines 10, 11, 12 and 13 have 36.8%, 21.0%, 21.0% and 21.0% of probability to be selected respectively.

I tried to use the formula sample_n like this:
a <- sample_n(demobel_matched, 1, weight = demobel_matched$weightPercent, replace = TRUE)

However, this does not return the thing I want and I got an error saying "incorrect number of probabilities" in this formula. So I think sample_n may not achieve the function I want.

Hence, I am wondering if you have any suggestions or existing known formulas to achieve my goal? Thanks very much for your kind help in advance!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.