简体   繁体   中英

How to sample from a vector without repeating?

Good afternoon !

I need to sample elements from a vector but without repeating. This means if i have a vector of n elements, i will take an element each time by random & i will store the element in a table. The next time my initial table will not contain the element selected before.

ex:

a = c(1,2,0,7,5)
sample(a,1) give 5 for example. 
print(a) ; a now should contain only 1 , 2 , 0 , 7.

I wish my question is clear. Thank you for help !

Another approach is to sample an index value and subset based on it:

a <- c(1, 2, 0, 7, 5)

set.seed(123)
ind <- sample(seq_along(a), 1)

a[ind]
a[-ind]

I think the solution could be:

a = c(1,2,0,7,5)
a=a[!a %in% sample(a,1)] ;

will sample the element & delete it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM