R:合并两个向量并以最大重复次数将其洗牌
我想合并R中的两个向量。每个向量有30个相等的值,例如:R:合并两个向量并以最大重复次数将其洗牌,r,R,我想合并R中的两个向量。每个向量有30个相等的值,例如: a <- rep("a",30) b <- rep("b",30) a试试看 我认为post表明它们应该是30个相等的值,如果(sum(v1==a)=sum(v1==b))中断,则可以在 c <- c("a","a","b","b","b","a","b","a","a",...) f1 <- function(x,y, n1, n2 ){ repeat { v1 <- sample(c(x,y)
a <- rep("a",30)
b <- rep("b",30)
a试试看
我认为post表明它们应该是30个相等的值,如果(sum(v1==a)=sum(v1==b))中断,则可以在
c <- c("a","a","b","b","b","a","b","a","a",...)
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
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
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