使用R在 Dataframe 中生成随机因子对

qij5mzcb  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(120)

我有一个字符向量 Dataframe ,我想随机生成来自这个向量的名称对。我的代码给出了所有的组合。但我想生成所有的名称应该配对一次在随机顺序;一个项目不能与自身合作。我的代码是:

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

短暂性脑缺血发作

dojqjjoe

dojqjjoe1#

从“名称”列获取unique元素,将其sample并转换为具有2列的matrix(假设唯一元素的长度为偶数)

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

相关问题