# Suppose I have a vector:
myvec = c(1,0,3,0,77,9,0,1,2,0)
# I want to randomly pick an element from myvec
# where element == 0
# and print the value of the corresponding index.
# So, for example I might randomly pick the 3rd 0
# and I would print the corresponding index
# which is 7,
# My
Not only does it not require a loop, this is a one-liner:
myvec - c(1,0,3,0,77,9,0,1,2,0)
sample(which(myvec == 0), 1)
[1] 4
sample(which(myvec == 0), 1)
[1] 7
sample(which(myvec == 0), 1)
[1] 2
If there's a possibility of not having zeros then you'll need to check
that separately, otherwise
Typo fix below:
On Thu, Oct 17, 2013 at 3:05 PM, Sarah Goslee sarah.gos...@gmail.com wrote:
Not only does it not require a loop, this is a one-liner:
myvec - c(1,0,3,0,77,9,0,1,2,0)
sample(which(myvec == 0), 1)
[1] 4
sample(which(myvec == 0), 1)
[1] 7
sample(which(myvec == 0), 1)
[1] 2
On 10/17/2013 11:54 AM, Stock Beaver wrote:
# Suppose I have a vector:
myvec = c(1,0,3,0,77,9,0,1,2,0)
# I want to randomly pick an element from myvec
# where element == 0
# and print the value of the corresponding index.
# So, for example I might randomly pick the 3rd 0
# and I would
4 matches
Mail list logo