title: R: Call a pasted variable name and use it as position argument
body: <p>I am trying to replace all values of r for which r&lt;=10 with the value of the 1st observation in x (which is 1). This is just a very simplified example of what I am trying to do, so please do not question why I'm trying to do this in a complicated way because the full code is more complicated. The only thing I need help with is figuring out how to use the vector I created (p1) to replace r[p1] or equivalently r[c(1,2,3,4)] with x[ 1 ] (which is equal to 1). I can not write p1 explicitly because it will be generated in a loop (not shown in code).  </p>
  
  <pre><code>x=c(1,2,3)
  r=c(1,3,7,10,15)
  assign(paste0("p", x[1]), which(r&lt;=10))
  p1
  r[paste0("p", x[1])]=x[1]
  </code></pre>
  
  <p>In the code above, I tried using <code>r[paste0("p", x[1])]=x[1]</code>  but this is the output I end up with<a href="https://i.stack.imgur.com/9EpH8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9EpH8.png" alt="enter image description here"></a></p>
  
  <p>When instead I would like to see this output
  <a href="https://i.stack.imgur.com/X6XhG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X6XhG.png" alt="enter image description here"></a></p>
  
  <p>Basically, I need to figure out a way to call p1 in this code <code>r[??]=x[1]</code>  without explicitly typing p1.</p>
  
  <p>I have included the full code I am attempting below in case context is needed.</p>
  
  <pre><code>##Creates a function to generate discrete random values from a specified pmf
  ##n is the number of random values you wish to generate
  ##x is a vector of discrete values (e.g. c(1,2,3))
  ##pmf is the associated pmf for the discrete values (e.g. c(.3,.2,.5)) 
  r.dscrt.pmf=function(n,x,pmf){
      set.seed(1)
      ##Generate n uniform random values from 0 to 1
      r=runif(n)
      high=0
      low=0
      for (i in 1:length(x)){
          ##High will establish the appropriate upper bound to consider
          high=high+pmf[i]
          if (i==1){
              ##Creates the variable p1 which contains the positions of all
              ##r less than or equal to the first value of pmf
              assign(paste0("p", x[i]), which(r&lt;=pmf[i]))
          } else { 
              ##Creates the variable p2,p3,p4,etc. which contains the positions of all
              ##r between the appropriate interval of high and low
              assign(paste0("p", x[i]), which(r&gt;low &amp; r&lt;=high))
          }
          ##Low will establish the appropriate lower bound to consider
          low=low+pmf[i]
      }
      for (i in 1:length(x)){
          ##Will loops to replace the values of r at the positions specified at 
          ##p1,p2,p3,etc. with x[1],x[2],x[3],etc. respectively.
          r[paste0("p", x[i])]=x[i]
      }
      ##Returns the new r 
      r
  }
  ##Example call of the function
  r.dscrt.pmf(10,c(0,1,3),c(.3,.2,.5))
  </code></pre>