我有一個任務,我完全不知道如何開始使它作業。
我必須創建單詞串列的變體,其中每個字符(第一個和最后一個之間)將在不同位置用“*”替換。
它應該看起來像這樣:
輸入:c('煙霧','刺痛')
所需的輸出:'s*og'、'sm*g'、's**g'、's*ing'、'st*ng'、'sti*g'、's***g'
知道如何實作這樣的目標嗎?
非常感謝
更新 我找到了這個解決方案:
s <- c( 'smog')
f <- function(x,y) {substr(x,y,y) <- "*"; x}
g <- function(x) Reduce(f,x,s)
unlist(lapply(1:(nchar(s)-2),function(x) combn(2:(nchar(s)-1),x,g)))
output:
[1] "s*og" "sm*g" "s**g"
唯一的問題是,它僅在字串中有一個單詞時才有效,而不是幾個
uj5u.com熱心網友回復:
有關相關技術,另請參閱此 SO 帖子:在字串中創建所有字母替換組合
編輯
從 OP 編輯??和評論:
repfun2 <- function(s){
f <- function(x,y) {substr(x,y,y) <- "*"; x}
g <- function(x) Reduce(f,x,s)
out <- unlist(lapply(1:(nchar(s)-2),function(x) combn(2:(nchar(s)-1),x,g)))
return(out)
}
lapply(test2, FUN = repfun2)
輸出:
> lapply(test2, FUN = repfun2)
[[1]]
[1] "s*og" "sm*g" "s**g"
[[2]]
[1] "s*ing" "st*ng" "sti*g" "s**ng" "s*i*g" "st**g" "s***g"
上一個隨機替換的答案
我了解您希望隨機替換字串向量中的字符。如果這是正確的,這是一個想法:
test2 <- c('smog', 'sting')
repfun <- function(.string) {
n_char <- nchar(.string)
# random selection of n characters that will be replaced in the string
repchar <- sample(1:n_char, size = sample(1:n_char, size = 1))
# replacing the characters in the string
for(i in seq_along(repchar)) substring(.string, repchar[i], repchar[i]) <- "*"
return(.string)
}
lapply(test2, FUN = repfun)
一些輸出:
> lapply(test2, FUN = repfun)
[[1]]
[1] "*mog"
[[2]]
[1] "s*ing"
> lapply(test2, FUN = repfun)
[[1]]
[1] "s*o*"
[[2]]
[1] "s*i*g"
基本思想是:
- 確定字串中的字符數,
- 根據長度隨機采樣,
- 用“*”替換隨機采樣的字符
- 用于
lapply傳遞字串向量。
我認為您可以根據需要通過洗掉for回圈來改進它,請在此處和此處查看一些想法
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451727.html
