samedi 24 mars 2018

Function with random experiment related to value pairs

I have two vectors x1 and p:

x1 <- c(1,2,3,1,2,3)
p <- c(0.1,0.9,0.9,0.1,0.5,0.7)

Both vectors form pairs of values, see df1:

df1 <- data.frame(x1,p)
> df1
  x1   p
1  1 0.1
2  2 0.9
3  3 0.9
4  1 0.1
5  2 0.5
6  3 0.7

Following function is used to update vector df1$x1 to a vector df1$x2, depending on a random experiment and a probability p:

rexp <- function(x,p){
  if(runif(1) <= p) return(x + 1)
  return(x)
}

Using lapply, the function "rexp" is applied to every df1$x1 value. Depending on the random experiment, the value for x2 remains equal x1 or increases by + 1. In the follwing example, p equals 0.5:

set.seed(123)
df1$x2 <- unlist(lapply(df1$x1,rexp,0.5))

> df1
  x1   p x2
1  1 0.1  2
2  2 0.9  2
3  3 0.9  4
4  1 0.1  1
5  2 0.5  2
6  3 0.7  4

Now to my problem: I want the argument "p" in "rexp" to refer to the vector df1$p. For example, p for df1$x1[1] should be 0.1 (as can be seen in df1$p[1]): unlist(lapply(df1$x1[1],rexp,df1$p[1])). p for df1$x1[5] should be df1$p[5], which is 0.5: unlist(lapply(df1$x1[5],rexp,df1$p[5]))

Desired output should be something like:

> unlist(lapply(df1$x1,rexp,df1$p))
[1] 1 3 4 1 2 4
#where 1 refers to rexp(df1$x1[1],df1$p[1]),
#3 refers to rexp(df1$x1[2],df1$p[2]),
#4 refers to rexp(df1$x1[3],df1$p[3]) and so on... 

Doing that "manually" leads to:

set.seed(123)
> unlist(lapply(df1$x1[1],rexp,df1$p[1]))
[1] 1
> unlist(lapply(df1$x1[2],rexp,df1$p[2]))
[1] 3
> unlist(lapply(df1$x1[3],rexp,df1$p[3]))
[1] 4
> unlist(lapply(df1$x1[4],rexp,df1$p[4]))
[1] 1
> unlist(lapply(df1$x1[5],rexp,df1$p[5]))
[1] 2
> unlist(lapply(df1$x1[6],rexp,df1$p[6]))
[1] 4

How can "rexp" be adjusted so that the function uses the specific df1$p-value for each df1$x1-value? Note: At this point, using "lapply" is important, because for every df1$x1-value in the function "rexp" a new random number should be drawn. I am happy about any help!




Aucun commentaire:

Enregistrer un commentaire