生成一个插值字符串n次,这样我得到n个不同的答案

时间:2017-07-28 06:19:21

标签: r

我正在尝试从选项列表中创建虚拟数据:

library('stringr')
#Generate a load of strings
line <- list(x1 = 10, x2 = 30,x3="There is no intestinal metaplasia, dysplasia or malignancy",x4="No Helicobacter are seen",x5="There is some ulceration",x6="There is no intercellular oedema in the surface epithelium",x7="PASstaining shows occasional spores, consistent with candida",x8="No herpetic viral inclusions are seen",x9="There is no dysplasia and no invasive carcinoma",x10="There is mild regenerative epithelial change, but neither dysplasia nor malignancy is seen",x11="The appearances are consistent with the endoscopic diagnosis of Barrett's oesophagus with active chronic inflammation",x12="The biopsies of oesophageal squamous mucosa show surface erosion and active chronic inflammation",x13="Numerous Candida spores and hyphae are present admixed with ulcer slough",x14="There is reactive basal cell hyperplasia and mild inflammatory epithelial atypia",x15="There is no significant increase in intraepithelialeosinophils",x16="No granulomas or viral inclusions are seen",x17="The appearances are those of Candida oesophagitis",x18="Neither dysplasia nor malignancy is seen",x19="The appearances are consistent with, but not specific for Barrett's (columnar lined) oesophagus")
listofResults<-unlist(sample(line,2,replace=T))
list.of.samples <- replicate(1000, paste(sample(1:10,1), "specimens collected the largest measuring", sample(1:5,1) ,"x", sample(1:5,1) ,"x", sample(1:5,1), "mm and the smallest", sample(1:5,1) ,"x", sample(1:5,1) ,"x", sample(1:5,1), "mm"), simplify=FALSE)

我想创建10个数据样本。如果我跑:

#Merge the strings together randomly
histop<-paste (sample(list.of.samples,1,replace=T),str_c(sample(line,sample(3:10,1),replace=T),collapse='.'))   

然后我得到随机构造的字符串就好了,正如预期的那样,每次运行它都会改变。无论如何运行

rep(histop,10)

只得到相同结果10次。所以我试着把它作为一个函数来代表

histop<-function(){
  paste (sample(list.of.samples,1,replace=T),str_c(sample(line,sample(3:10,1),replace=T),collapse='.'))   
}
rep(histop(),10)

但我得到了相同的结果。如何获得10个不同的字符串?

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我只需要使用replicate而不是rep。我需要阅读有关此内容,但我认为复制实际上会运行该行,而rep会运行一次,然后复制结果。

replicate(20,paste (sample(list.of.samples,1,replace=T),str_c(sample(line,sample(3:10,1),replace=T),collapse='.')))