[R] Newb: How I find random vector index?

2013-10-17 Thread Stock Beaver
# 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

Re: [R] Newb: How I find random vector index?

2013-10-17 Thread Sarah Goslee
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

Re: [R] Newb: How I find random vector index?

2013-10-17 Thread Sarah Goslee
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

Re: [R] Newb: How I find random vector index?

2013-10-17 Thread Brian Diggs
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