The goal of the function I am trying to write is to do the following
N
between 0 and 10.eq(N) = P
.L
randomly between 0 and 1.L > P
, we discard this number, but otherwise, we add P
to a vector of numbers.runs
, the input of our function.Trying to run neutronrejector
leads to several errors though:
Error: unexpected '=' in:
" U <- U+1
if(U ="
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in "}"
Those are the error messages. My code is below. Could anyone take a look at this and see what I am doing wrong? I am completely new to writing functions in R, I am more used to using preset packages.
eq = function(x){x*(exp(-x/1.4))}
values <- c()
U <- 0
neutronrejector = function(runs){
repeat{
N = runif(1, min=0, max=10)
P = eq(N)
L = runif(100, min=0, max=1)
ifelse(L > P, , values = c(N, values))
U = U+1
if(U = runs) break
}
}
A few corrections:
==
runif(1,min=0,max=1)
to get one random numberif
statement instead of ifelse
neutronrejector = function(runs){
repeat{
N = runif(1, min=0, max=10)
P = eq(N)
L = runif(1, min=0, max=1)
if (L > P) values = c(N, values)
U = U+1
if(U == runs) break
}
values
}
neutronrejector(10)
[1] 4.997457 7.699111 7.009196 5.515345 3.422422 9.495239 8.758963 2.209809 6.392655