这似乎是一个非常有趣的问题,尽管它可能只是因为我误解了它才显得有趣——我在这里得到的解决方案创建length of character vector / frequency of most frequent item
子向量,然后将每个字符串放入f
这些子向量中,f
该字符串的频率在哪里。这可能比您实际要求的要复杂。
library(plyr)
# I created a file with 10000 random strings and a roughly similar frequency
# distribution using python, and now I can't remember exactly what I did
strings <- read.csv("random_strings.txt", header=FALSE,
stringsAsFactors=FALSE)$V1
freq_table <- table(strings)
num_sub_vectors <- max(freq_table)
# Create a list of empty character vectors
split_list <- alply(1:num_sub_vectors, 1, function(x) return(character(0)))
for (s in names(freq_table)) {
# Put each string into f of the sub-vectors, where f is the string's
# frequency
freq <- freq_table[[s]]
# Choose f random indexes to put this string into
sub_vecs <- sample(1:num_sub_vectors, freq)
for (sub in sub_vecs) {
split_list[[sub]] <- c(split_list[[sub]], s)
}
}
要测试它是否有效,请选择一个字符串s
或一个频率f
,并检查子向量中s
出现的情况。f
重复直到你有信心。
> head(freq_table[freq_table==15])
strings
ad ak bj cg cl cy
15 15 15 15 15 15
> sum(sapply(split_list, function(x) "ad" %in% x))
[1] 15