如何将某些字母锁定到位,同时打乱一系列字母中剩余的字母?

问题描述 投票:0回答:3

我有以下字母序列:

"MGGGRYSGTK"

我希望将所有

G
保留在同一位置,但将其余字母打乱。到目前为止我的代码如下。我需要有关如何将
G
插回原来位置的帮助。

sequence <- "MGGGRYSGTK"

# Find the positions of Gs in the sequence
G_positions <- which(sequence == "G")

# Remove the Gs from the sequence
sequence_no_G <- gsub("G", "", sequence)

# Shuffle the remaining amino acids
shuffled_sequence_no_G <- paste(sample(strsplit(sequence_no_G, "")[[1]]), collapse = "")
r
3个回答
0
投票

这似乎是使用

iterators
包的好机会,它维护有关状态的信息,因此可以轻松请求下一个元素。

迭代器是一种特殊类型的对象,它概括了循环变量的概念。当作为参数传递给知道如何处理它的函数时,迭代器提供一系列 价值观。

首先将字符串拆分为字母向量,然后迭代其长度,选择(取决于它是哪个字母)所需的字母或迭代器提供的下一个随机字母。

library(iterators)
swap_letters <- function(str, letter) {
    x <- strsplit(str, "")[[1]]
    hold <- which(x == letter)

    swap <- iter(sample(x[x != letter]))

    lapply(
        seq_along(x),
        \(i, h = hold, s = swap, l = letter) if (i %in% h) l else nextElem(s)
    ) |> paste(collapse = "")
}

set.seed(42)
swap_letters("MGGGRYSGTK", "G") # "MGGGTKSGRY"
swap_letters("MGGGRYSGTK", "M") # "MGKGRGYTGS"

0
投票

以最少的基础更改您的代码:

sequence = "MGGGRYSGTK"
g = unlist(gregexpr("G", sequence))
x = unlist(strsplit(sequence, split = ""))
x[-g] = sample(x[-g])
paste(x, collapse = "") 
[1] "KGGGTMRGYS"

0
投票

您可以使用

utf8ToInt
intToUtf8
+
sample
,如下所示

s <- "MGGGRYSGTK"
f <- function(s, keep = "G") {
    sint <- utf8ToInt(s)
    idx <- sint != utf8ToInt(keep)
    intToUtf8(replace(sint, which(idx), sample(sint[idx])))
}

你会看到例子

> f(s)
[1] "KGGGRSMGTY"
© www.soinside.com 2019 - 2024. All rights reserved.