Random pairing in R

If I have 2 datasets (in the example below names and car companies) how to I get R/Rstudio to randomly pair an item from each dataset?

I don't want Jack to always be selected with Kia, I want R to randomly pick a car company for Jack.

d <- data.frame( name = c("bob", "jack", "carl", "jill"),
site = c("honda", "kia", "ford", "toyota"))

sample_n(d, 2)

sample_n(d, 2)
name site
1 jack kia
2 jill toyota

Hi @MOT675 and welcome to the RStudio community :partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

You could use a combination of the sample() and paste() functions:

set.seed(123)

name <- c("bob", "jack", "carl", "jill")
site <- c("honda", "kia", "ford", "toyota")
random_pairing <- paste(sample(name), sample(site), sep = "-")

random_pairing
[1] "carl-ford"  "jill-kia"   "bob-toyota" "jack-honda"

Note that I used a seed number just for my answer to be reproducible. If you keep rerunning the code; however, you will keep getting different results.

Thank you for the feedback. The code you provided was very helpful in addressing my question.

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.