从较大字符串(R)中随机抽样固定长度子字符串

时间:2015-10-11 21:07:52

标签: r string random-sample

我有一个大约1000个字符的长字符串(称之为SuperString),我想从SuperString中随机抽取100个子字符串。

每个子字符串的长度应为10个字符,子字符串中的字符应与SuperString中的字符顺序相同。

示例:

SuperString = "ADKFKDSLFSDHKENNCNEUNCIEOCIKEMNKSDFU...KJSDLJDFSKLDJSLJ"
substrings = ["FSDHKENNCN", "ADKFKDSLFS", ... ,"OCIKEMNKS"]

1 个答案:

答案 0 :(得分:3)

# Create a SuperString
set.seed(87)
SuperString = paste(sample(LETTERS, 1000, replace=TRUE), collapse="")

# Function to sample 10 characters in a row, starting at a random point
# in the string
sampleString = function(string) {
    nStart = sample(1:991,1)
    substr(string, nStart, nStart + 9)
}

# Run the function 100 times
substrings = replicate(100, sampleString(SuperString))

substrings
[1] "VEOUELBFTD" "OPTCIDDNXK" "SFHNKKGOWR" "RVJQYYUSAZ" "MQMBMKCTTI" "ZKLWETGMVR"
[7] "OOXFLGCGPX" "DXAVUMQMBM" "HOORFCFABC" "AMOYPOXXRA" "TGKWKKZUEK" "UYPRPYQCMU" 
...
[91] "RZNSLOBFBK" "FKUKMDUQIK" "YGXDXAVUMQ" "SIRAMRBXSH" "TAILZPHZYS" "OEOUTGKWKK"
[97] "XFLGCGPXKZ" "EDRVJQYYUS" "RHUZLBFNQX" "MUWUODCCFT"