Reputation: 730
I have two vectors:
x <- c(1, 2, 3, 4)
y <- c(5, 6, 7, 8, 9, 10)
now i want to resample n times to such that the numbers of the two vectors can shuffle randomly and maintain their dimension. Eg.
at n = 1
x <- c(2, 4, 7, 1)
y <- c(3, 9, 8, 6, 5, 10)
at n = 2
x <- c(5, 6, 10, 3)
y <- c(1, 9, 8, 4, 2, 7)
how can i accomplish this in R?
Upvotes: 1
Views: 1224
Reputation: 206566
You could define your own helper function like
resample <- function(x,y) {
xx <- sample(c(x,y))
list(x=xx[1:length(x)], y=xx[-(1:length(x))])
}
and then use it with
# set.seed(15)
r1 <- resample(x,y)
r1$x
# [1] 7 2 8 5
r1$y
# [1] 3 10 4 1 9 6
r2 <- resample(x,y)
r2$x
# [1] 2 6 5 8
r2$y
# [1] 9 7 10 3 1 4
But it seems like you might be permuting case/control labels or something? In that case, you might have a vector of group assignments
group <- rep(c("x","y"), c(length(x),length(y)))
and then you could just sample() that each time to mix up groups
# set.seed(15)
(g1<-sample(group))
# [1] "y" "x" "y" "y" "x" "y" "x" "x" "y" "y"
(g2<-sample(group))
# [1] "x" "y" "y" "y" "y" "y" "y" "x" "x" "x"
and you could extract indexes with
which(g1=="x")
# [1] 2 5 7 8
which(g1=="y")
# [1] 1 3 4 6 9 10
if you really needed to.
Upvotes: 3