sapply() 在 R 中行为不端
sapply() misbehaving in R
我正在尝试让 R 使用 sapply()
将 c(1/2, 1, sqrt(2)/2 )
替换为 rscale =
参数。但我想知道为什么我得到 3 个相同的答案(应该得到 3 个不同的答案)?
ttype = 1
t = -.742
N1 = 102
N2 = ifelse(ttype==1, NA, 102)
rscale = sqrt(2)/2
tl = 1
dexp = -1
library(BayesFactor)
Gi1 <- ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval =
c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = rscale, simple = TRUE)
UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), function(rscale) Gi1 )## HERE I get 3 same answers!
正如@HubertL 所说,Gi1 是一个数字,而不是一个函数。您需要编写一个函数,该函数接受一个参数并计算其上的 ttest.tstat,将新变量插入 "rscale" 参数。例如,
library(BayesFactor)
Gi1 <- function(x) {
ttest.tstat(t, N1, ifelse(ttype==1, F, N2),
nullInterval = c(ifelse(dexp==-1, -Inf, Inf),
ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE) }
UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), Gi1)
UrUr
你应该会得到三个不同的答案。
同意前面的回答。您也可以尝试像这样使用 sapply:
sapply(c(1/2, 1, sqrt(2)/2), function(x) ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval = c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE))
Sapply 然后将使用参数 "x" 作为向量 c 中每个元素的占位符循环遍历向量。
我正在尝试让 R 使用 sapply()
将 c(1/2, 1, sqrt(2)/2 )
替换为 rscale =
参数。但我想知道为什么我得到 3 个相同的答案(应该得到 3 个不同的答案)?
ttype = 1
t = -.742
N1 = 102
N2 = ifelse(ttype==1, NA, 102)
rscale = sqrt(2)/2
tl = 1
dexp = -1
library(BayesFactor)
Gi1 <- ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval =
c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = rscale, simple = TRUE)
UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), function(rscale) Gi1 )## HERE I get 3 same answers!
正如@HubertL 所说,Gi1 是一个数字,而不是一个函数。您需要编写一个函数,该函数接受一个参数并计算其上的 ttest.tstat,将新变量插入 "rscale" 参数。例如,
library(BayesFactor)
Gi1 <- function(x) {
ttest.tstat(t, N1, ifelse(ttype==1, F, N2),
nullInterval = c(ifelse(dexp==-1, -Inf, Inf),
ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE) }
UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), Gi1)
UrUr
你应该会得到三个不同的答案。
同意前面的回答。您也可以尝试像这样使用 sapply:
sapply(c(1/2, 1, sqrt(2)/2), function(x) ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval = c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE))
Sapply 然后将使用参数 "x" 作为向量 c 中每个元素的占位符循环遍历向量。