如何在 for 循环之后获取 x 中的全部元素以在 R 中绘图?

How to get the entire elements in x after the for loop for plotting in R?

我想知道如何在 for-loop[=20= 之后获取向量 x 的整个 5 个元素] 就像我在下面的 R 代码中得到向量 ts5 元素:

if(!require(BayesFactor)){install.packages('BayesFactor')} ; library(BayesFactor)

ts = numeric(5)
x = numeric(5)

for(i in 1:5){

 x = c(1, 3, 10, 30, 100)[i]

 f <- function(t){
 abs(ttest.tstat( t, 50, 50, rscale = sqrt(2)/2, simple = TRUE)[[1]] - x)
 }

 ts[i] = optimize(f, interval = c(-6, 6))[[1]]
  }

plot(ts, x, t = "o") #`x` contains only the last element (i.e., 100) of the `x` vector above

您可以在循环之前启动 x 向量,然后在循环中引用它。这样你之后仍然可以拥有它。

x = c(1, 3, 10, 30, 100)

for(i in 1:5){

    x_int = x[i]

    f <- function(t){
        abs(ttest.tstat( t, 50, 50, rscale = sqrt(2)/2, simple = TRUE)[[1]] - x_int)
    }

    ts[i] = optimize(f, interval = c(-6, 6))[[1]]
}

plot(ts, x, t = "o")

这是一个使用sapply的等效操作(我还没有测试过这个,请自己测试,如果它没有按预期工作,请告诉我):

x = c(1, 3, 10, 30, 100)

f <- function(t, x_int){
    abs(ttest.tstat( t, 50, 50, rscale = sqrt(2)/2, simple = TRUE)[[1]] - x_int)
}

ts <- sapply( x, function(i) optimize(f, interval = c(-6, 6), x_int = i)[[1]] )

plot(ts, x, t = "o")