R:合并两个向量并以最大重复次数对它们进行混洗

时间:2015-03-03 04:00:37

标签: r

我想在R中合并两个向量。每个有30个相等的值,例如:

a <- rep("a",30)
b <- rep("b",30)

如何实现在结果向量中连续出现a或b的次数超过三次?

c <- c("a","a","b","b","b","a","b","a","a",...)

1 个答案:

答案 0 :(得分:2)

尝试

f1 <- function(x,y, n1, n2 ){
 repeat {
   v1 <- sample(c(x,y),n1, replace=TRUE)
    if(all(rle(v1)$lengths <=n2)) break
    }
  return(v1)
}

res <- f1(a,b, 20, 3)
res
#[1] "a" "a" "b" "b" "a" "b" "b" "a" "b" "a" "b" "b" "b" "a" "a"
# "a" "b" "a" "b"
#[20] "a"
rle(res)$lengths
#[1] 2 2 1 2 1 1 1 3 3 1 1 1 1
rle(f1(a,b, 30, 2))$lengths
#[1] 1 2 1 1 2 2 2 1 1 2 2 1 2 1 1 1 1 2 1 2 1

基于@jbest的评论,如果你需要结果具有相同数量的“a”,“b”元素,

 f1N <- function(x,y, n1, n2 ){
   repeat {
    v1 <- sample(c(x,y),n1, replace=TRUE)
    if(all(rle(v1)$lengths <=n2) & !diff(table(v1))) break
  }
  return(v1)
 }

 res <- f1N(a,b,36,2)
 table(res)
 #res
 # a  b 
 #18 18 

更新

您也可能没有寻找变量n1。以下函数将返回60个元素的向量(30个“a”和30个“b”)

  f2 <- function(x, y, n){
  repeat {
   v1 <- sample(c(x,y))
    if(all(rle(v1)$lengths <=n)) break
   }
  return(v1)
 }
 res <- f2(a,b,3)
rle(res)$lengths
#[1] 2 1 3 1 3 1 1 2 1 1 1 1 1 1 1 2 3 1 1 2 2 1 1 2 1 3 1 3 1 3 2 1 2 2 2 2 1
 table(res)
 #res
 #a  b 
 #30 30