R:调用粘贴的变量名并将其用作位置参数

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

我正在尝试将 r <=10 的所有 r 值替换为 x 中第一个观察值(即 1)。这只是我尝试做的一个非常简单的例子,所以请不要质疑我为什么要尝试以复杂的方式来做这件事,因为完整的代码更复杂。我唯一需要帮助的是弄清楚如何使用我创建的向量 (p1) 替换 r[p1] 或等效的 r[c(1,2,3,4)] 与 x[ 1 ](等于到 1).我无法显式编写 p1,因为它将在循环中生成(未在代码中显示)。

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]

在上面的代码中,我尝试使用 r[paste0("p", x[1])]=x[1] 但这是我最终得到的输出

什么时候我想看到这个输出

基本上,我需要找出一种在这段代码中调用 p1 的方法 r[??]=x[1] 而无需显式键入 p1。

我在下面包含了我正在尝试的完整代码,以防需要上下文。

##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))

这符合您的需求吗?

ifelse(r<11, x[1], r)
[1]  1  1  1  1 15

get 类似于 assign,因为它允许您通过字符串而不是名称来引用变量。

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

但是 get 是 "flags" 可以用更清晰、更安全的方式编写的东西之一。