Monday, July 23, 2012

Draw n values from a defined set


# This is a simple function (program in Stata) that takes an input vector of values (d) and randomly draws from them a random subset set of values of length n.

# We want a to program our own function to draw x draws from a set of possible draws
pull <- function(n,d) {
  # Create an empty vector to store the output
  v <- c()
  # Loop from 1 to n and draw 1 observation from 1 randomly for each of those
  for(i in 1:n) v=append(v, d[ceiling(runif(1)*length(d))])
    # Okay so I know this looks pretty intractable.  The for loop allows a singe line of code to follow on the same line.  So it is just saying loop through i from 1 to n.  Then the vector v has one value added to the end of it.  That value is a random draw from the vector d.
  # Return the compiled vector of random draws v
  v
}

# Now let's see how well our little code works.
pull(20,c("Agent Bob","Agent Sue","008","Agent Henrietta"))

# This will draw five numbers randomly between 1 and 10
pull(5,1:10)

# One can do this same kind of thing in Stata.  However, it would be much less elegant.

###########
# After writing this function I realized my original solution was not nearly as elegant as it could have been.
###########


# We want a to program our own function to draw x draws from a set of possible draws
pull <- function(n,d) d[ceiling(runif(n)*length(d))]

# Now let's see how well our little code works.
pull(20,c("Agent Bob","Agent Sue","008","Agent Henrietta"))

# This will draw five numbers randomly between 1 and 10
pull(5,1:10)


# This alternative function specification uses the preferred vector forms in R's language.
# To get a hint of what it is doing play around with this.
vect1 <- c("a","b","c","d","e")
# To see vect1 just type
vect1

# To get a single element of vect1
vect1[2]

# To get a subset of vect1
vect1[c(1,2,3)]

# To get a subset with repetition
vect1[c(1,2,1,3,1)]

#Now
ceiling(runif(20)*length(vect1))

# This is a nice way of figuring out how code is working in R.  Simply take it apart and see what it does by itself.

No comments:

Post a Comment