我沒有回圈經驗,需要一個回圈來:
- 對資料框進行下采樣
- 在測驗中執行并存盤結果
- 提取置信限
- 向資料框添加置信限
- 并重做 100 次并將每次迭代附加到串列中。下面是一次迭代的代碼。我想要一個 100 行 2 列的資料框,即上限和下限
df = c(3,5,4,3,2,6,7,5,4,2,3,4,5,7,8,4,3,2,6,8,9,7,6,5,4,2,3,4,3,2,3,4,56,7,87) # dummy data
df2 = (sample(df, 20)) # take 20 samples of df data
tt = t.test(df2) # perform t test and store results
cl = tt$conf.int # extract only the upper and lower confidence limits and store
cl_list = data.frame(cl) # make into a dataframe
cl_list = t(cl_list) # transpose dataframe so that col_1 is the Lower UCL and col_2 is the Upper
uj5u.com熱心網友回復:
您可以使用lapply(),然后使用do.call(rbind,...)矩陣,設定為 data.frame,并重命名列:
setNames(data.frame(do.call(rbind,
lapply(1:100, function(x) {
t(t.test(sample(df,20))$conf.int)
})
)),c("lower", "upper"))
輸出:(前六行 100)
lower upper
1 1.7378652 21.56213
2 0.4650324 17.73497
3 0.5198734 17.78013
4 1.9602563 12.83974
5 1.3473073 12.35269
6 0.2490264 17.55097
你也可以使用replicate
setNames(data.frame(
t(replicate(t.test(sample(df,20))$conf.int,n=100))
), c("lower", "upper"))
輸出(同樣,前六行,100 行,不同的輸出,沒有種子集)
lower upper
1 0.5774575 17.822543
2 3.5952854 5.404715
3 3.7792077 5.720792
4 1.7471739 21.552826
5 0.9553992 20.944601
6 2.4087922 13.191208
您還可以使用傳統的 for 回圈,如下所示:
result = matrix(NA,nrow = 100,ncol = 2)
for(i in 1:100) {
result[i,] <- t(t.test(sample(df,20))$conf.int)
}
setNames(data.frame(result), c("lower", "upper"))
輸出:
lower upper
1 2.23601345 13.06399
2 -0.07824891 17.27825
3 0.12547144 17.47453
4 1.96874001 12.83126
5 0.19719426 17.50281
6 3.34230034 4.85770
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452307.html
下一篇:如何在r中的列上使用摘要庫
