问题
I have written a code to generate logistic random variables in R but with a truncation between 0.2 and 0.5. Can anyone there help write it properly especially with the if conditions. Thank you.
<##The Logistic distribution##
ns=10
for(i in 1:100){
rtruncl=function(u,a,b,alpha1,alpha2)
#error: {
qalpha1 = log(alpha1/(1-alpha1))
qalpha2 = log((1-alpha2)/alpha2)
X=a+b*log(u/(1-u))
u=runif(ns)
if((X >= qalpha1) && (X <= qalpha2)){
# error: }
a=0; b=2 ##a is a location parameter and b is a scale parameter##
t1=rtruncl(u,a,b, 0.2,0.5)
t1
}
} #closed the for loop
回答1:
You can do this using the built-in logistic distribution functions in R (e.g., rlogis(...)
, along with the truncdist
package.
library(truncdist)
location <- 0
scale <- 2
X <- rlogis(1000, location=location, scale=scale)
Y <- rtrunc(1000, spec="logis", a=-5,b=5, location=location, scale=scale)
par(mfrow=c(1,2))
hist(X, xlim=c(-10,10), breaks=30, freq=F, col="lightgreen")
hist(Y, xlim=c(-10,10), breaks=30, freq=F, col="lightblue")

If this is some kind of homework assignment, to show how truncated distributions are calculated, then I suggest you look at the code for the rtrunc(...)
function.
来源:https://stackoverflow.com/questions/22685549/simulation-to-generate-random-numbers-from-a-truncated-logistic-distribution-in