mtext()的选择性文本基于R中的输入参数?

时间:2017-09-21 03:07:42

标签: r function plot histogram

我有一个矢量化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?

1 个答案:

答案 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))

enter image description here

现在,如果您实施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)

enter image description here

解决此问题的一种方法是将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?

enter image description here