Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random pairs of factors in dataframe using R

I have a character vector data frame and I would like to randomly generate pairs of names coming from this vector. My code gives the all combinations. But I want to generate all names should be paired with one time in random order; an item cannot be partner with itself.
My code is:

# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish", "John", "ruban", "mary", "barath", "leema", "joshi", "indhu", "praveen", "joshua",
             "alex", "martin", "stella", "veronica", "henry", "rajesh", "yusuf", "jenita", "johana", "jerald", "jegan", "lincy",
             "jona", "rani", "julie", "ross", "chandler", "monica", "penny", "sheldon"),
  
  "Sex" = c("Female", "Male", "Male", "male", "male", "Female", "male", "Female", "Female", "Female", "male",
            "male", "male", "male", "Female", "Female", "male", "male", "male", "Female", "Female", "male",
            "male", "Female", "Female", "Female", "Female", "male", "male", "Female", "Female", "male"),
  
  "Number" = c(8937998889, 2598279874, 4589987483, 2876876877, 2876876876, 2487698798, 2879879877, 2887987897, 2878798733,
               4309808098, 8748098990, 9883798798, 8734787987, 8973498787, 8734887877, 9798374877, 8786487687, 7275687263,
               4379879847, 8943787876, 3874879874, 8978973987, 8978347878, 8839478768, 9378887774, 8467676764, 7246276874,
               7478798743, 6576787877, 7328776876, 6648678833, 6378787878)
)
print(df)

# Accessing first and second column
cat("Accessing first and second column\n")
dat <- print(df[, 1])

t(combn(unique(dat,2)))

TIA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Get the unique elements from ‘Name’ column, sample it and convert to a matrix with 2 columns (assuming the length of unique elements are even)

matrix(sample(unique(df$Name)), ncol = 2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading