我有一个矢量化R函数,可以产生一些直方图(如下)。我想在其中一个直方图中添加mtext()
(请在下面找到)。
但我希望mtext()
中的文字根据参数n
是否是长度为>的向量而改变。 1 OR参数es
是长度为>的向量。 1。
在我的代码中,我没有成功使用以下内容:
txt = if(length(n) > 1) "Group Sample Size = " else if(length(es) > 1) "Effect Size = " else "Group Sample Size = "
mtext(paste0(txt, input), 3)
[请在下面找到这些]
以下是我的完整R代码:
p.es = function(n, es, n.sim){
input = if(length(n) > 1) n else if(length(es) > 1) es else n
t.sim = Vectorize(function(n, es){
d = numeric(n.sim)
p = numeric(n.sim)
for(i in 1:n.sim){
N = sqrt((n^2)/(2*n))
x = rnorm(n, es, 1)
y = rnorm(n, 0, 1)
a = t.test(x, y, var.equal = TRUE)
d[i] = a[[1]]/N
p[i] = a[[3]] }
txt = if(length(n) > 1) "Group Sample Size = " else if(length(es) > 1) "Effect Size = " else "Group Sample Size = "
hist(p) ; mtext(paste0(txt, input), 3) ## Here I need help!!!!
hist(d)
}, c("n", "es"))
par(mfcol = c(2, length(input)), xpd = NA)
invisible(t.sim(n, es)) }
# Example of use:
p.es(n = 20, es = c(.1, .2), n.sim = 20) # Here I expect the mtext to show "Effect Size = "
# but it doesn't why?
答案 0 :(得分:0)
我认为问题不在于您mtext
语句的if...else
。由于Vectorize
,问题发生了。让我们从你的内部函数开始,这里称为myfun
。它看起来效果很好。
myfun <- function(n, es, nsim, input){
d = numeric(n.sim)
p = numeric(n.sim)
for(i in 1:n.sim){
N = sqrt((n^2)/(2*n))
x = rnorm(n, es, 1)
y = rnorm(n, 0, 1)
a = t.test(x, y, var.equal = TRUE)
d[i] = a[[1]]/N
p[i] = a[[3]] }
txt <- if (length(n) > 1) {"Group Sample Size = "} else if (length(es) > 1) {"Effect Size = "} else {"Group Sample Size = "}
hist(p) ; mtext(paste0(txt, input, collapse = " "), 3) ## Here I need help!!!!
hist(d)
}
# Test Run
par(mfrow = c(1,2))
myfun(n = 10,
es = c(0.1, 0.2),
nsim = 10,
input = c(0.1, 0.2))
现在,如果您实施Vectorize
,则会出现问题。
t.sim <- Vectorize(myfun, c('n', 'es', 'nsim', 'input'))
n <- 10
n.sim <- 10
es <- c(0.1, 0.2)
input <- c(0.1, 0.2)
t.sim(n, es, n.sim, input)
解决此问题的一种方法是将txt
分配移到Vectorize
来电之外(当您定义txt
时,是否可以指定input
的值?)。< / p>
p.es = function(n, es, n.sim){
input = if(length(n) > 1) n else if(length(es) > 1) es else n
txt = if(length(n) > 1) "Group Sample Size = " else if(length(es) > 1) "Effect Size = " else "Group Sample Size = "
t.sim = Vectorize(function(n, es){
d = numeric(n.sim)
p = numeric(n.sim)
for(i in 1:n.sim){
N = sqrt((n^2)/(2*n))
x = rnorm(n, es, 1)
y = rnorm(n, 0, 1)
a = t.test(x, y, var.equal = TRUE)
d[i] = a[[1]]/N
p[i] = a[[3]] }
hist(p) ; mtext(paste0(txt, paste(input, collapse = "-")), 3) ## Here I need help!!!!
hist(d)
}, c("n", "es"))
par(mfcol = c(2, length(input)), xpd = NA)
invisible(t.sim(n, es)) }
# Example of use:
p.es(n = 20, es = c(.1, .2), n.sim = 20) # Is this what you want?