我试图用 x 中第一个观察值(即 1)替换 r<=10 的所有 r 值。这只是我想要做的事情的一个非常简单的例子,所以请不要质疑为什么我试图以复杂的方式来做这件事,因为完整的代码更复杂。我唯一需要帮助的是弄清楚如何使用我创建的向量 (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]
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我尝试使用,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))
Run Code Online (Sandbox Code Playgroud)
get就像 一样assign,它允许您通过字符串而不是名称来引用变量。
r[get(paste0("p", x[1]))]=x[1]
Run Code Online (Sandbox Code Playgroud)
但这get是可以用更清晰、更安全的方式编写的“标志”之一。