跨字符向量列表的样本

时间:2018-04-03 15:01:05

标签: r

问题

我想将短语"COMPARTMENT_START"替换为短语xy,其中" y" part是我的数据框中的采样数

输入

structure(list(report = c("COMPARTMENT_START duod biospies taken WritePathReport NUMBER OF BIOPSIES: biopsied x8 COMPARTMENT_END\", \"COMPARTMENT_START duod biospies taken", 
"COMPARTMENT_START oesophagus biospies taken WritePathReport NUMBER OF BIOPSIES: character(0) COMPARTMENT_END\", \"COMPARTMENT_START duod biospies taken", 
"\", \"COMPARTMENT_START duod biospies taken", "COMPARTMENT_START duod biospies taken"
)), .Names = "report", row.names = 979:982, class = "data.frame")

输出应为:

x3 duod biospies taken WritePathReport NUMBER OF BIOPSIES: biopsied x8 COMPARTMENT_END", "x5 duod biospies taken
x2 oesophagus biospies taken WritePathReport NUMBER OF BIOPSIES: character(0) COMPARTMENT_END", "x1 duod biospies taken                                                                                                            ", "x1 duod biospies taken                                                                                                                 x3x duod biospies taken

我尝试过:

lapply(dff3$report,function(x) paste(gsub("COMPARTMENT_START",paste0("x"sample(3:10,1)),x)))

但我明白了:

"x8 duod biospies taken WritePathReport NUMBER OF BIOPSIES: biopsied x8 COMPARTMENT_END\", \"x8 duod biospies taken"    
"x3 oesophagus biospies taken WritePathReport NUMBER OF BIOPSIES: character(0) COMPARTMENT_END\", \"x3 duod biospies taken"
"\", \"x5 duod biospies taken"    
"x5 duod biospies taken"

如何进行采样以在列表中的矢量元素之间获取不同的数字,然后作为数据帧输出回来?

1 个答案:

答案 0 :(得分:2)

我们可以使用gsubfn

library(gsubfn)
df1$report <- gsubfn("(COMPARTMENT_START)",
            function(x) paste0("x", sample(3:10, 1)), df1$report)
df1$report
#[1] "x7 duod biospies taken WritePathReport NUMBER OF BIOPSIES: biopsied x8 COMPARTMENT_END\", \"x6 duod biospies taken"        
#[2] "x10 oesophagus biospies taken WritePathReport NUMBER OF BIOPSIES: character(0) COMPARTMENT_END\", \"x9 duod biospies taken"
#[3] "\", \"x8 duod biospies taken"                                                                                              
#[4] "x10 duod biospies taken"