[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 initial approach is to use a for-loop.
# Also I take a short-cut which assumes myvec is short:

elm = 1
while (elm != 0) {
  # Pick a random index, (it might be a 0):
  rndidx = round(runif(1, min=1, max=length(myvec)))
  elm = myvec[rndidx]
  if(elm == 0)
    print(I am done)
  else
    print(I am not done)
}
print(rndidx)

# If myvec is large and/or contains no zeros,
# The above loop is sub-optimal/faulty.

# I suspect that skilled R-people would approach this task differently.
# Perhaps they would use features baked into R rather than use a loop?
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] A 'good' way to build a matrix from a sequence of integers?

2013-10-15 Thread Stock Beaver
# I understand that a good way to build a vector from a sequence of integers,
# is to use syntax like this:
myvec = c(1:99)

# Here is the 'short' version of my question:
# I want to understand a 'good' way to build a matrix from a sequence of 
integers.

# If that question is not clear, here is a longer version:

# Here is what I did for a 1D-matrix:

# I pick the sequence 1:3
# I build a vector:
vec1x3 = c(1:3)
vec1x3
# I transform it into a 1 x 3 matrix:
m1x3 = matrix(vec1x3, c(length(vec1x3),1))
m1x3
#  [,1]
# [1,]    1
# [2,]    2
# [3,]    3
#  

# That was easy.

# Next I want to expand from a 1 x 3 matrix to a 2 x 9 matrix
# which contains all combinations of 1:3

# So the first 4 rows would look like this:
# 1 1
# 1 2
# 1 3 I call this a rowvec
# 2 1

# My first idea is write a loop like this:

for (i in 1:3) {
  for(j in 1:3) {
    rowvec = c(i,j)
    # Place rowvec in matrix
  }
}

# I'm curious if a skilled R-person would do it differently?
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.