通常,隐式循环比显式循环更快。尝试将代码放入循环中并将其放入函数中,然后在 lapply 或 sapply 语句中使用该函数。
myfunction = function(<insert relevant parameters here>)
{
X.sample <- X[ sample(1:nrow(X), 40, replace = FALSE), ]
X.sample.1 <- X.sample[1:20, ]
X.sample.2 <- X.sample[21:40, ]
Y <- as.data.frame(cbind(X.sample.1$ID, X.sample.1$x, X.sample.2$ID, X.sample.2$x))
cor.results <- cor.test(Y[,2], Y[,4], alternative = c("greater"), method = c("pearson"))
cor.results$estimate
}
Z = sapply(x, myfunction)
#Here every element of x contains the arguments you want to pass to my function
#You can pass multiple arguments separated by commas after the function name
error <- qt(0.975, df = (length(Z) - 1)) * (sd(Z))/sqrt(length(Z))
你可以这样做,但我发现如果可以的话,最好只使用包boot()
中的函数boot
。
至于set.seed()
您需要在每次生成随机任何东西之前直接设置它。见下文。
> rnorm(6)
[1] 1.0915017 -0.6229437 -0.9074604 -1.5937133 0.3026445 1.6343924
> set.seed(1001)
> rnorm(6)
[1] 2.1886481 -0.1775473 -0.1852753 -2.5065362 -0.5573113 -0.1435595
> set.seed(1001)
> rnorm(6)
[1] 2.1886481 -0.1775473 -0.1852753 -2.5065362 -0.5573113 -0.1435595
> rnorm(6)
[1] 1.0915017 -0.6229437 -0.9074604 -1.5937133 0.3026445 1.6343924
> set.seed(1001)
> sample(1:5,10,replace=T)
[1] 5 3 3 3 3 5 1 1 2 4
> sample(1:5,10,replace=T)
[1] 3 1 5 3 2 5 1 2 1 4
> set.seed(1001)
> sample(1:5,10,replace=T)
[1] 5 3 3 3 3 5 1 1 2 4
> rnorm(6)
[1] -0.1435595 1.0915017 -0.6229437 -0.9074604 -1.5937133 0.3026445
> set.seed(1001)
> rnorm(6)
[1] 2.1886481 -0.1775473 -0.1852753 -2.5065362 -0.5573113 -0.1435595
希望有帮助!
在研究这个boot
函数给你一个例子时,我遇到了一个障碍。它只返回一行。奇怪的!我可能会对此提出一个新问题。无论如何,我认为包bootstrap()
中的功能bootstrap
将满足您的需求。这是我的例子
set.seed(1001)
X <- rnorm(600, 7, 2)
myStat <- function(x, pairs) {
index = sample(1:length(x),(pairs*2))
Z = cor(X[index[1:(length(index)/2)]], X[index[((length(index)/2)+1):length(index)]])
return(Z)
}
b=bootstrap(X,1000,myStat,pairs=20)
Z <- b$thetastar
error <- qt(0.975, length(Z)-1 * sd(Z)/sqrt(length(Z)))