在矢量中插入随机间隙

时间:2016-06-12 11:07:40

标签: r function

我有一个蛋白质序列(例如,载体Responsive.makeResponsive(this);

我想实现一个函数来在该序列中插入随机间隙"I" "D" "I" "A" "S"

我该怎么做?

2 个答案:

答案 0 :(得分:0)

例如

f <- function(x) { 
  id <- sample(seq(x), 1)
  c(x[1:id], "*", x[-(1:id)])
}
set.seed(123)
f(c("I", "D", "I", "A", "S"))
# [1] "I" "D" "*" "I" "A" "S"
f(c("I", "D", "I", "A", "S"))
# [1] "I" "D" "I" "A" "*" "S"

答案 1 :(得分:0)

你可以尝试:

func_insert_at <- function(vec, elements, at){
x <- rep(NA, length(vec)+length(elements));
x[at] <- elements;x[-at] <- vec;x;}

vec <- c("I", "D", "I", "A", "S")
set.seed(23)
func_insert_at(vec, "*", ceiling(runif(1, 0, length(vec))))
# [1] "I" "D" "*" "I" "A" "S"
func_insert_at(vec, "*", ceiling(runif(1, 0, length(vec))))
# [1] "I" "*" "D" "I" "A" "S"

此函数的优点是函数的elements参数可以是任意长度(不是特定1)。例如,

elements=c("M", "O", "H")
positions=c(1,3,6)
func_insert_at(vec, elements, positions)
# [1] "M" "I" "O" "D" "I" "H" "A" "S"