Search code examples
rpositionpaste

R: Call a pasted variable name and use it as position argument


I am trying to replace all values of r for which r<=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).

x=c(1,2,3)
r=c(1,3,7,10,15)
assign(paste0("p", x[1]), which(r<=10))
p1
r[paste0("p", x[1])]=x[1]

In the code above, I tried using r[paste0("p", x[1])]=x[1] but this is the output I end up withenter image description here

When instead I would like to see this output enter image description here

Basically, I need to figure out a way to call p1 in this code r[??]=x[1] without explicitly typing p1.

I have included the full code I am attempting below in case context is needed.

##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<=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>low & r<=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))

Solution

  • get is like assign, in that it lets you refer to variables by string instead of name.

    r[get(paste0("p", x[1]))]=x[1]
    

    But get is one of those "flags" of something that could be written in a much clearer and safer way.